中介者模式的定义为:Define an object that encapsulates how a set of objects
interact.Mediator promotes loose coupling by keeping objects from referring to each other
explicitly,and it lets you vary their interaction independently.(用一个中介对象封装一系列的对象
交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,而且可以独立地改变它
interact.Mediator promotes loose coupling by keeping objects from referring to each other
explicitly,and it lets you vary their interaction independently.(用一个中介对象封装一系列的对象
交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,而且可以独立地改变它
们之间的交互。)
public abstract class Mediator {
//定义同事类
protected ConcreteColleague1 c1;
protected ConcreteColleague2 c2;
//通过getter/setter方法把同事类注入进来
public ConcreteColleague1 getC1() {
return c1;
}
public void setC1(ConcreteColleague1 c1) {
this.c1 = c1;
}
public ConcreteColleague2 getC2() {
return c2;
}
public void setC2(ConcreteColleague2 c2) {
this.c2 = c2;
}
//中介者模式的业务逻辑
public abstract void doSomething1();
public abstract void doSomething2();
}
中介者模式的优点就是减少类间的依赖,把原有的一对多的依赖变成了一对一的依赖,
同事类只依赖中介者,减少了依赖,当然同时也降低了类间的耦合。