设计模式-中介者模式(Mediator)

中介者模式(Mediator)

用一个中介对象来封装一系列对象的交互,中介者使各对象不需要显式地互相调用,而是通过中介者。达到解耦及独立变化(只影响到中介者)。
也叫:调停者模式

设计模式-中介者模式(Mediator)_第1张图片
中介者模式.png

优缺点:

  • 优点:

    ConcreteCollegue 之间解耦,独立变化(只影响中介者)
    各对象之间由:网状结构-->星状结构
    对象之间通过中介者间接发生关系
    
  • 缺点:

    中介者的责任太重,需要知道所有的具体对象。
    对象之间的关系需要通过中介者来调用,导致中介者逻辑会越来越复杂。
    

应用场景

适用于存在一系列类似功能的组件,而组件不能过多。例如:

  • 例如计算器的按键
  • 各个国家和联合国
设计模式-中介者模式(Mediator)_第2张图片
没有联合国之前.png
设计模式-中介者模式(Mediator)_第3张图片
有了联合国后.png

中介者模式实现

设计模式-中介者模式(Mediator)_第4张图片
中介者模式.png
设计模式-中介者模式(Mediator)_第5张图片
调用流程.png
设计模式-中介者模式(Mediator)_第6张图片
目录结构.png
  • Mediator
public abstract class Mediator {
    public abstract void expressDeclare(String msg, Country countrt);
}
  • Country
public abstract class Country {

    protected Mediator mediator;

    public Country(Mediator m) {
        this.mediator = m;
    }

    public abstract void makeDeclere();
    public abstract void express(String msg);

}
  • ConcreteMediator
public class ConcreteMediator extends Mediator {

    public USA usa;
    public Iraq iraq;

    @Override
    public void expressDeclare(String msg, Country country) {
        if (country == this.usa) {
            usa.express(msg);
        } else if (country == this.iraq) {
            iraq.express(msg);
        }
    }

}
  • Iraq
public class Iraq extends Country {

    public Iraq(Mediator m) {
        super(m);
    }

    @Override
    public void makeDeclere() {
        mediator.expressDeclare("我不随便搞事情", this);
    }
    
    @Override
    public void express(String msg) {
        System.out.println(msg);
    }

}
  • USA
public class USA extends Country {

    public USA(Mediator m) {
        super(m);
    }

    @Override
    public void makeDeclere() {
        mediator.expressDeclare("我是老大,随便你怎么搞", this);
    }

    @Override
    public void express(String msg) {
        System.out.println(msg);
    }

}
  • Client
public class Client {

    public static void main(String[] args) {
        ConcreteMediator mediator = new ConcreteMediator();

        Iraq iraq = new Iraq(mediator);
        USA usa = new USA(mediator);

        mediator.iraq = iraq;
        mediator.usa = usa;

        iraq.makeDeclere();
        usa.makeDeclere();


    }

}

参考:

  • 《大话设计模式》 第三版
  • 《android源码设计模式》

你可能感兴趣的:(设计模式-中介者模式(Mediator))