本文主要分析设计模式中介者模式(Mediator pattern) : 使用中介者模式来集中相关对象之间复杂的沟通和控制方式。
中介者模式(Mediator)是一种行为设计模式, 能让你减少对象之间混乱无序的依赖关系。 该模式会限制对象之间的直接交互, 迫使它们通过一个中介者对象进行合作。
Mediator : 为 Colleague 对象定义一个交流接口。
- abstract class Mediator {
- public abstract void Send(String message, Colleague colleague);
- }
ConcreteMediator : 实现 Mediator 中的交流接口。 这个类中需要了解并维护所有的 colleague 对象。
- class ConcreteMediator extends 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 if (colleague == colleague2){
- colleague1.Notify(message);
- } else {
- System.out.println("Error!");
- }
- }
- }
Colleague 组 : 每个 Colleague 对象应该知道它的 Mediator 对象,但不知道其他同事对象。它只能联系 Mediator 对象。
- abstract class Colleague {
- protected Mediator mediator;
-
- public Colleague(Mediator mediator) {
- this.mediator = mediator;
- }
-
- public void Send(String message) {
- mediator.Send(message, this);
- }
-
- public abstract void Notify(String message);
- }
-
- class ConcreteColleague1 extends Colleague {
- public ConcreteColleague1(Mediator mediator) {
- super(mediator);
- }
-
- @Override
- public void Notify(String message) {
- System.out.println("同事1得到信息:" + message);
- }
- }
-
- class ConcreteColleague2 extends Colleague {
- public ConcreteColleague2(Mediator mediator) {
- super(mediator);
- }
-
- @Override
- public void Notify(String message) {
- System.out.println("同事2得到信息:" + message);
- }
- }
- public class MediatorPattern {
- 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("How are you?");
- colleague2.Send("Fine, thank you. And you?");
- colleague1.Send("I'm fine. Thankes.");
- }
- }
-
- ------------------------------------------------------------------------------
-
- 同事2得到信息:How are you?
- 同事1得到信息:Fine, thank you. And you?
- 同事2得到信息:I'm fine. Thankes.
-