设计模式之中介者模式(行为型)--- 18

  • 一、导语
  • 二、怎么用
    1.样例背景
    2.UML类图
    3.代码示例
  • 三、优缺点
  • 四、使用场景
    1.概括描述
    2.现存知名产品中的使用示例
  • 五、相关设计模式
  • 六、参考

一、导语

中介者模式(Mediator,又叫做调停者模式),用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立的改变他们之间的交互。

二、怎么用

共有2个示例,代码详见访问链接
下面以example2举例说明

1. 样例背景

以联合国和各国家之间的关系举例
中介者:联合国
同事类:各国家

没使用中介者模式时的关系图
使用中介者模式时的关系图

2. UML类图

UnitedNations ------------------- 抽象中介者
SecurityCouncil ----------------- 实际中介者
Country ------------------------- 抽象同事类
Iraq ----------------------------- 实际同事类
USA ---------------------------- 实际同事类

example2 使用中介者模式后 UML类图

3. 代码示例

/**
 * description:  联合国机构  (抽象的中介者)
 */
public abstract class UnitedNations {
    abstract void declare(Country colleague, String message);
}


/**
 * description:  安理会 (具体的中介者类)
 */
public class SecurityCouncil extends UnitedNations {
    @Override
    void declare(Country colleague, String message) {
        colleague.sendMessage(message);
    }
}


/**
 * description:  抽象的国家 (抽象的同事类)
 */
public abstract class Country {
    protected UnitedNations mediator;

    public Country(UnitedNations mediator) {
        this.mediator = mediator;
    }

    abstract void declare(String message);
    abstract void sendMessage(String message);
}


/**
 * description:  伊拉克 (具体的同事类)
 */
public class Iraq extends Country {

    public Iraq(UnitedNations mediator) {
        super(mediator);
    }

    @Override
    void declare(String message) {
        mediator.declare(this,message);
    }

    @Override
    void sendMessage(String message) {
        System.out.println("伊拉克说: " + message);
    }
}


/**
 * description:  美国 (具体的同事类)
 */
public class USA extends Country {
    public USA(UnitedNations mediator) {
        super(mediator);
    }

    @Override
    void declare(String message) {
        mediator.declare(this,message);
    }

    @Override
    void sendMessage(String message) {
        System.out.println("USA说: " + message);
    }
}


public class Test {
    public static void main(String[] args) {
        UnitedNations securityCouncil = new SecurityCouncil();

        Country usa = new USA(securityCouncil);
        Country iraq = new Iraq(securityCouncil);

        usa.declare("不准研制核武器,否则老子收拾你");
        iraq.declare("老子想干啥就干啥,用你管");
    }
}

执行结果

USA说: 不准研制核武器,否则老子收拾你
伊拉克说: 老子想干啥就干啥,用你管

三、优缺点

  • 缺点
    1.中介者过多时会增加系统的复杂度

  • 优点
    1.将一对多转化为一对一、降低程序复杂度
    2.类之间解耦

四、使用场景

1. 概括描述

  • 系统中对象之间存在复杂的引用关系,产生的相互依赖关系结构混乱且难以理解
  • 交互的公共行为,如果需要改变行为则可以增加新的中介者类

2. 现存知名产品中的使用示例 todo

2.1 java.util.timer (jdk)

五、相关设计模式

1. 中介者模式和观察者模式

这两个有时候会结合使用,有时候我们会使用观察者模式来实现中介者模式中角色的通讯。

六、参考

  1. https://coding.imooc.com/learn/list/270.html(强烈推荐)
  2. https://en.wikipedia.org/wiki/Design_Patterns
  3. 大话设计模式,电子版下载链接,https://pan.baidu.com/s/17WOI3Bvp-JUoQXvaomHISg 密码:vw05
    (作者博客,https://www.cnblogs.com/cj723/archive/2007/12/30/1021314.html)
  4. https://www.cnblogs.com/geek6/p/3951677.html

你可能感兴趣的:(设计模式之中介者模式(行为型)--- 18)