概念:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
核心:处理多对多关系,对对象如何协作进行了抽象,集中控制
缺点:导致中介者类复杂性上升
中介者模式结构图
java代码
public class MediatorTest {
public static void main(String[] args) {
ConcreteMediator concreteMediator = new ConcreteMediator();
ConcreteColleague1 concreteColleague1 = new ConcreteColleague1(concreteMediator);
ConcreteColleague2 concreteColleague2 = new ConcreteColleague2(concreteMediator);
concreteMediator.setConcreteColleague1(concreteColleague1);
concreteMediator.setConcreteColleague2(concreteColleague2);
concreteColleague1.Send();
concreteColleague2.Send();
}
}
//中介者
public abstract class Mediator {
public abstract void Send(String message, Colleague colleague);
}
//中介者实现类
public class ConcreteMediator extends Mediator{
private ConcreteColleague1 concreteColleague1;
private ConcreteColleague2 concreteColleague2;
public void setConcreteColleague1(ConcreteColleague1 concreteColleague1){
this.concreteColleague1 = concreteColleague1;
}
public void setConcreteColleague2(ConcreteColleague2 concreteColleague2){
this.concreteColleague2 = concreteColleague2;
}
@Override
public void Send(String message, Colleague colleague) {
if (colleague == concreteColleague1){
concreteColleague2.Notify(message);
}else{
concreteColleague1.Notify(message);
}
}
}
//抽象同事类
public abstract class Colleague {
Mediator mediator;
public Colleague(Mediator mediator){
this.mediator = mediator;
}
public abstract void Send();
public abstract void Notify(String message);
}
//同事1
public class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
}
@Override
public void Send() {
mediator.Send("我是同事1发送的消息", this);
}
@Override
public void Notify(String message) {
System.out.println("同事1得到信息:" + message);
}
}
//同事2
public class ConcreteColleague2 extends Colleague{
public ConcreteColleague2(Mediator mediator) {
super(mediator);
}
@Override
public void Send() {
mediator.Send("我是同事2发送的消息", this);
}
@Override
public void Notify(String message) {
System.out.println("同事2得到信息:" + message);
}
}