描述: 中介者设计模式是用来降低多个对象和类之间通信的复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,代码易于维护。中介模式属于行为型模式
核心思想: 对象与对象之间存在大量的关联关系,这样势必会导致系统结构变的很复杂,同时若一个对象发生变化,我们也需要跟踪与之相关联的对象,同时做出相应的处理
使用场景:
- 系统中对对象之间存在比较复杂的引用关系,导致它们之间的依赖关系结构混乱而且难以服用改对象
- 想通过一个中间类来封装多个类中的行为,而不像生成太多的子类
中介者设计模式的优点:
- 降低了类的复杂度将一对多转化为一对一
- 各个类之间解耦
- 符合迪米特法则
中介者设计模式的缺点:
示例:
1 2 3 4
| interface Mediator { void send(String message, Colleague colleague);
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class ConcreteMediator implements 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 send(String message, Colleague colleague) { if (colleague == colleague1) { colleague2.notify(message); } else { colleague1.notify(message); } }
}
|
1 2 3 4 5 6 7 8 9
| abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) { this.mediator = mediator; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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("同事1得到消息:" + message); }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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("同事1得到消息:" + message); }
}
|
1 2 3 4 5 6 7 8 9 10 11 12
| public static void main(String[] args) { ConcreteMediator mediator = new ConcreteMediator();
ConcreteColleague1 colleague1 = new ConcreteColleague1(mediator); ConcreteColleague2 colleague2 = new ConcreteColleague2(mediator);
mediator.setColleague1(colleague1); mediator.setColleague2(colleague2);
colleague1.send("Nice to meet u."); colleague2.send("Nice to meet u too."); }
|