中介者模式(行为型)

一:背景

当在一个系统中,存在大量的对象的时候,对象之间的相互调用连接会大大增加系统的复杂性,对系统行为的改动也会变得十分困难;根据‘迪米特法则’,如果两个类不必彼此直接通信,那么这两个类就不应该发生直接的相互作用。这里,我们就可以引入一个中介者,将系统的网状结构变成以中介者为中心的星形结构。

二:概述

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

2、类图结构
中介者

三:实例分析

下面拿大话设计模式中联合国的例子来说
中介者
对应于类图,联合国就相当于一个中介者,用以传递国家之间的消息。
代码:

联合国

public abstract class UnitedNations {
    public abstract void declare(String message, Country colleague);
}

国家

public abstract class Country {
    protected UnitedNations mediator;

    public Country(UnitedNations mediator){
        this.mediator = mediator;
    }
    public void declare(String message){
        mediator.declare(message, this);
    }
    public void getMessage(String message){
        System.out.println(message);
    }
}

联合国的实现类:联合国安理会

public class UnitedNationsSecurityCouncil extends UnitedNations {
    //定义了两个国家之间的交互
    private Country colleague1;
    private Country colleague2;

    public void setColleague1(Country usa){
        colleague1 = usa;
    }
    public void setColleague2(Country iraq){
        colleague2 = iraq;
    }
    @Override
    public void declare(String message, Country colleague) {
        if (colleague == colleague1){
            colleague2.getMessage(message);
        }else{
            colleague1.getMessage(message);
        }
    }
}

具体国家:
美国

public class USA extends Country {

    public USA(UnitedNations mediator) {
        super(mediator);
    }
    //声明
    public void declare(String message){
        mediator.declare(message, this);
    }
    //获得消息
    public void getMessage(String message){
        System.out.println("USA获取消息:"+message);
    }
}

伊拉克

public class Iraq extends Country {

    public Iraq(UnitedNations mediator) {
        super(mediator);
    }
    //声明
    public void declare(String message){
        mediator.declare(message,this);
    }
    //获取消息
    public void getMessage(String message){
        System.out.println("Iraq获取消息:"+message);
    }
}

来看看客户端是如何操作的:

UnitedNationsSecurityCouncil unsc = new UnitedNationsSecurityCouncil();

Country usa = new USA(unsc);
Country iraq = new Iraq(unsc);
unsc.setColleague1(usa);
unsc.setColleague2(iraq);

usa.declare("不要挑衅我!");
iraq.declare("喜欢挑衅你。");

中介者模式一般应用于一组对象以定义良好但是复杂的方式进行通信的场合,如.NET中的Form窗体就是一个中介者;但是由于ConcreteMediator控制了集中化,于是把交互复杂性变成了中介者的复杂性,这就使得中介者会变得比任何一个ConcreteColleague都复杂。

参考书籍:《大话设计模式》

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值