美文网首页Android知识Android开发经验谈Android开发
设计模式-中介者模式(Mediator)

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

作者: 小菜_charry | 来源:发表于2017-07-31 15:54 被阅读77次

    中介者模式(Mediator)

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

    中介者模式.png

    优缺点:

    • 优点:

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

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

    应用场景

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

    • 例如计算器的按键
    • 各个国家和联合国
    没有联合国之前.png 有了联合国后.png

    中介者模式实现

    中介者模式.png 调用流程.png 目录结构.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)

        本文链接:https://www.haomeiwen.com/subject/khxrlxtx.html