设计模式之中介者模式

中介者模式的定义是:用一个中介对象封装一系列的对象交互,中介者使各对象不需要显式地相互作用,从而使其耦合松散,而且可以独立地改变它
们之间的交互。

中介者模式适合于组件之间过于耦合而不方便修改的情况。因为中介者模式强制组件之间只通过中介者交互,而不是组件之间直接交互,避免组件之间相互依赖紧密耦合,方便于修改。类所拥有的依赖关系越少, 就越易于修改、 扩展或复用。

因为交互都是通过中介者来实现,所以需要在中介者中定义交互的所有方法。

ComponentA
-m:Mediator
+operationA()
ComponentB
-m:Mediator
+operationB()
«interface»
Mediator
+notify()
ConcrateMediator
- ComponentA
- ComponentB
+notify()
+operationA()
+operationB()

代码实现:

// 抽象组件
public abstract class Plane {  
    protected Mediator mediator;  
  
    public void setMediator(Mediator mediator) {  
        this.mediator = mediator;  
    }  
  
    abstract void notifyMsg(String msg);  
  
    abstract void receiveMsg(String msg);  
}
public class PlaneA extends Plane {  
  
    @Override  
    public void notifyMsg(String msg) {  
        System.out.println("PlaneA 通知控制塔:" + msg);  
        mediator.notifyOtherPlane(this, msg);  
    }  
  
    @Override  
    public void receiveMsg(String msg) {  
        System.out.println("PlaneA 收到控制塔通知:" + msg);  
    }  
}


public class PlaneB extends Plane {  
  
    @Override  
    public void notifyMsg(String msg) {  
        System.out.println("PlaneB 通知控制塔:"+msg);  
        mediator.notifyOtherPlane(this,msg);  
    }  
  
    @Override  
    public void receiveMsg(String msg) {  
        System.out.println("PlaneB 收到控制塔通知:"+msg);  
    }  
}
// 抽象中介者
public interface Mediator {  
    void notifyOtherPlane(Plane plane, String msg);  
}
public class ControllerTower implements Mediator{  
    Plane planeA;  
    Plane planeB;  
  
    public void setPlaneA(Plane planeA) {  
        this.planeA = planeA;  
    }  
  
    public void setPlaneB(Plane planeB) {  
        this.planeB = planeB;  
    }  
  
    @Override  
    public void notifyOtherPlane(Plane plane, String msg) {  
        if(plane==planeA){  
            planeB.receiveMsg("PlanA 需要"+msg);  
        }else if(plane==planeB){  
            planeA.receiveMsg("PlanB 需要"+msg);  
        }  
    }  
}
Plane planeA=new PlaneA();  
Plane planeB=new PlaneB();  
ControllerTower tower=new ControllerTower();  
tower.setPlaneA(planeA);  
tower.setPlaneB(planeB);  
planeA.setMediator(tower);  
planeB.setMediator(tower);  
planeA.notifyMsg("起飞");

中介者模式的优点是减低组件间的耦合度,方便修改组件。

缺点是由于中介者需要定义组件间交互的所有方法,容易变成上帝对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值