中介者模式也称调停模式
中介者模式的定义: 用一个中介对象封装一系列对象(同事)的交互,中介者使各个对象不需要显式的的相互作用,从而使其耦合松散,而且可以独立地改变他们之间的交互。
中介者模式的参与者
抽象同事
public abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
}
具体同事
public class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
// TODO Auto-generated constructor stub
}
public void doingA1() {
System.out.println("Dong A1");
}
public void doingB1() {
System.out.println("Doing B1");
}
// 依赖方法
public void depB() {
super.mediator.doSomething2();
}
}
public class ConcreteColleague2 extends Colleague {
public ConcreteColleague2(Mediator mediator) {
super(mediator);
// TODO Auto-generated constructor stub
}
public void doingA2() {
System.out.println("Dong A2");
}
public void doingB2() {
System.out.println("Doing B2");
}
// 依赖方法
public void depA() {
super.mediator.doSomething1();
}
}
抽象中介者
public abstract class Mediator {
protected ConcreteColleague1 c1;
protected ConcreteColleague2 c2;
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();
}
具体中介者
public class ConcreteMediator extends Mediator{
@Override
public void doSomething1() {
super.c1.doingA1();
super.c2.doingA2();
}
@Override
public void doSomething2() {
super.c1.doingB1();
super.c2.doingB2();
}
}
中介者模式的优点
中介者模式的缺点
中介者模式的应用场景 如果在对象之间的关系呈现的像蜘蛛网的形状时,可以采用中介者模式将对像间的关系梳理呈星型关系