中介者模式,用一个中介者对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互。
package Mediator;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
ConcreteMediator mediator = new ConcreteMediator();
ConcreteColleague1 c1 = new ConcreteColleague1(mediator);
ConcreteColleague2 c2 = new ConcreteColleague2(mediator);
mediator.setColleague1(c1);
mediator.setColleague2(c2);
c1.send("ated?");
c2.send("not yet");
}
}
abstract class Mediator {
public abstract void sent(String message, Colleague colleague);
}
abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
}
class ConcreteMediator extends Mediator {
private ConcreteColleague1 colleague1;
private ConcreteColleague2 colleague2;
public void setColleague1(ConcreteColleague1 colleague1) {
this.colleague1 = colleague1;
}
public void setColleague2(ConcreteColleague2 colleague2) {
this.colleague2 = colleague2;
}
@Override
public void sent(String message, Colleague colleague) {
// TODO Auto-generated method stub
if (colleague == colleague1) {
colleague2.notifyy(message);
} else {
colleague1.notifyy(message);
}
}
}
class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
}
public void send(String message) {
mediator.sent(message, this);
}
public void notifyy(String message) {
System.out.println("colleague1 receive message:"+message);
}
}
class ConcreteColleague2 extends Colleague {
public ConcreteColleague2(Mediator mediator) {
super(mediator);
}
public void send(String message) {
mediator.sent(message, this);
}
public void notifyy(String message) {
System.out.println("colleague2 receive message:"+message);
}
}
Mediator和Colleague定义了接口,具体mediator持有具体colleague对象,消息的发送,从中介中转转发。类似于QQ聊天机制。
中介模式很容易在系统中应用,也很容易在系统中误用,当系统出现了多对多交互复杂的对象群时,不要急于使用中介者模式,而要先烦死你的系统在设计上是不是合理。
优点:Mediator的出现减少了各个Colleague的耦合,使得可以独立地改变和复用各个Colleague类和Mediator;由于把对象如何写作进行了抽象,将中介作为一个独立的概念并将其封装在一个对象中,这样关注的对象就从对象各自本身转移到他们之间的交互上来,也就是站在一个更宏观的角度去看待系统。
缺点:由于ConcreteMediator控制了集中化,于是就把交互复杂性变为了中介者的复杂性,这就使得中介者会变得比任何一个ConcreteColleague都复杂。
中介者模式一般应用于一组对象以定义良好但是复杂的方式进行通信的场合,以及想定制一个分布在多个类中的行为,而又不想生成太多的子类的场合。