设计模式—行为型模式之中介者模式
中介者模式(Mediator Pattern):用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,减少对象间混乱的依赖关系,从而使其耦合松散,而且可以独立地改变它们之间的交互。对象行为型模式。
包含以下角色:
-
Mediator: 抽象中介者
-
ConcreteMediator: 具体中介者
-
Colleague: 抽象同事类
-
ConcreteColleague: 具体同事类
示例
如下图所示,如果我们要几架飞机,互相联系的话,会很麻烦。如果有一个中间塔台来联系,就会方便很多。
代码如下:
/*** 抽象机长*/
public abstract class AbstarctCaptain {//起飞abstract void fly();//降落abstract void land();//完成abstract void success();}
/*** 塔台:中介者** 网状变为星状*/
public class ControlTower {private boolean canDo = true;//接受请求...public void acceptRequest(AbstarctCaptain captain,String action){if("fly".equals(action)||"land".equals(action)){if(canDo == true){System.out.println("允许......");canDo = false;}else {System.out.println("不允许.....");}}if("success".equals(action)){canDo = true;}}
}
具体机长:
public class CZ222 extends AbstarctCaptain{private ControlTower controlTower;public void setControlTower(ControlTower controlTower) {this.controlTower = controlTower;}@Overridevoid fly() {System.out.println("请求起飞");this.controlTower.acceptRequest(this,"fly");}@Overridevoid land() {System.out.println("请求降落");this.controlTower.acceptRequest(this,"land");}@Overridevoid success() {System.out.println("成功");this.controlTower.acceptRequest(this,"success");}
}
内部包含塔台;
其余两个类也是如此;
测试类如下:
public class MediatorTest {public static void main(String[] args) {ControlTower controlTower = new ControlTower();CZ222 cz222 = new CZ222();cz222.setControlTower(controlTower);EU111 eu111 = new EU111();eu111.setControlTower(controlTower);cz222.fly();eu111.fly();cz222.success();eu111.fly();eu111.success();}
}
运行结果如下: