中介者模式(Mediator Pattern)
定义一个对象封装一系列的对象交互,使得对象之间不需要显式地相互引用,从而使其耦合更加松散。并且还让我们可以独立变化多个对象相互引用。
?
要点:
????? 1、将多个对象间复杂的关联关系解耦,Mediator模式将多个对象间的控制逻辑进行集中管理,变“多个对象互相关联”为“多个对象和一个中介者关联”,简化了系统的维护,抵御了可能的变化。
????? 2、随着控制逻辑的复杂化,Mediator具体对象的实现可能相当复杂。这时候可以对Mediator对象进行分解处理。
????? 3、Facade模式是解耦系统外到系统内(单向)的对象关联关系;Mediator模式是解耦系统内各个对象之间(双向)的关联关系。
?
中介者接口类:
public interface Mediator {public void register(String name, Colleague c);public void call(String name, Colleague from);}?
中介者实现类:
public class ConcreteMediator implements Mediator{private Hashtable<String, Colleague> colleagues = new Hashtable<String, Colleague>();public void register(String name, Colleague c) {colleagues.put(name, c);}public void call(String name, Colleague from) {Colleague c = colleagues.get(name);if(c!=null){System.out.println(from.getName() + " call " + c.getName());}}}?
成员接口类:
public interface Colleague {public void call(String name);public String getName();}?
成员实现类1:
public class ConcreteColleague1 implements Colleague {private String name = "张三";private Mediator med;public ConcreteColleague1(Mediator med){this.med = med;this.med.register(this.name, this);}public String getName(){return this.name;}public void call(String name) {this.med.call(name, this);}}?
成员实现类2:
public class ConcreteColleague2 implements Colleague {private String name = "李四";private Mediator med;public ConcreteColleague2(Mediator med){this.med = med;this.med.register(this.name, this);}public String getName(){return this.name;}public void call(String name) {this.med.call(name, this);}}?