前言
什么时候使用中介者模式呢?
中介者模式就是在系统中对象关系比较复杂的情况下,就可以通过中介者模式来实现封装各个类的行为,以此来减少产生更多的类。
如图为题目
一、类图
二、具体步骤
1.创建抽象中介者接口AbsMediator
代码如下(示例):
//抽象中介者
public abstract class AbsMediator(){
protected List<AbsPeople> peoplelist = new ArrayList<AbsPeople>();//储存用户的信息
public void register(AbsPeople people){
peoplelist.add(people)//添加
people.setMediator(this);
}
//注册用户,实现一对多或多对多
public abstract void relay(AbsPeople talkContent)
}
2.创建抽象的用户类AbsPeople
代码如下(示例):
//抽象用户类
public abstract class AbsPeople{
protected AbsMediator mediator;//关联抽象中介者
public void setMediator(AbsMediator mediator){
this.mediator = mediator;
}
public void abstract send();//发送和接受消息
public void abstract receive();
}
3.创建具体中介者类Mediator
代码如下(示例):
public class Mediator extends AbsMediator{
public void relay(AbsPeople people){
for(AbsPeople p :peopleList){//循环向所有用户发送消息
if(!p.equals(people))//当前发送者不接收消息
p.receive();
}
}
}
4.创建具体中介者角色Student,Teacher类
代码如下(示例):
public class Student extends AbsPeople{
String name;
public Student(String name){this.name = name;}
public void send(){
System.out.println(name+"我发送了一条消息")
}
public void receive(){
System.out.println(name+"我收到一条消息")
}
}
public class Teacher extends AbsPeople{
String name;
public Teacher(String name){this.name = name}
public void send(){
System.out.println(name+"发送了一条消息");
}
public void receive(){
System.out.println(name+"我收到一条消息");
}
}
5.测试类Client
public class Client{
public static void main(String[] args) {
AbsMediator mediator = new AbsMediator();
AbsPeople student1,student2,teacher1,teacher2;
student1 = new Student("张三");
student2 = new Student("李四");
teacher1 = new Teacher("王五");
teacher2 = new Teacher("赵六");
mediator.register("student1 ");
mediator.register("student2 ");
mediator.register("teacher1 ");
mediator.register("teacher2 ");
student1.send();
student2.send();
teacher1.send();
teacher2.send();
}
}
6.结果
三、总结
中介者模式如类图所示,大致分为抽象中介者,抽象用户,而由这两个再分下级,就是具体中介者,具体用户了。
从而试下了对消息的模拟传输。