public abstract class Mediator { abstract public void Send(String message,Colleague colleague); }
public class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator=mediator; } }
public class ConcreteMediator extends Mediator { private ConcreteColleague1 colleague1; private ConcreteColleague2 colleague2; public ConcreteColleague1 getColleague1() { return colleague1; } public void setColleague1(ConcreteColleague1 colleague1) { this.colleague1=colleague1; } public ConcreteColleague2 getColleague2() { return colleague2; } public void setColleague2(ConcreteColleague2 colleague2) { this.colleague2=colleague2; } public void Send(String message,Colleague colleague) { if(colleague==colleague1) colleague2.Notify(message); if(colleague==colleague2) colleague1.Notify(message); } }
public class ConcreteColleague1 extends Colleague { public ConcreteColleague1(Mediator mediator) { super(mediator); } public void Send(String message) { mediator.Send(message,this); } public void Notify(String message) { System.out.println("colleague1 get message:"+message); } }
public class ConcreteColleague2 extends Colleague { public ConcreteColleague2(Mediator mediator) { super(mediator); } public void Send(String message) { mediator.Send(message,this); } public void Notify(String message) { System.out.println("colleague2 get message:"+message); } }
public class Main { public static void main(String[] args) { ConcreteMediator m=new ConcreteMediator(); ConcreteColleague1 c1=new ConcreteColleague1(m); ConcreteColleague2 c2=new ConcreteColleague2(m); m.setColleague1(c1); m.setColleague2(c2); c1.Send("Hello!"); c2.Send("Hello,too!"); } }中介者模式,定义一个中介对象来封装系列对象之间的交互。中介者使各个对象不需要显示地相互引用,从而使其耦合性松散,而且可以独立地改变他们之间的交互。一组定义良好的对象,现在要进行复杂的通信时或者定制一个分布在多个类中的行为,而又不想生成太多的子类时可以考虑使用中介者模式。可以看出,中介对象主要是用来封装行为的,行为的参与者就是那些对象,但是通过中介者,这些对象不用相互知道。使用中介者模式降低了系统对象之间的耦合性,使得对象易于独立的被复用;提高系统的灵活性,使得系统易于扩展和维护。同时,中介者模式的缺点也是显而易见的,因为这个中介承担了较多的责任,所以一旦出现问题,整个系统就会受到重大的影响。