中介者模式(Mediator)

中介者模式

一. 中介者模式

1.1 定义

  • 用一个中介者对象封装一系列的对象交互,中介者使各对象不需要显示的相互作用,从而使耦合松散,而且可以独立的改变他们之间的交互.

1.2 角色

  • 抽象中介者类(AbstractMediator).
  • 具体中介者实现类(Mediator).
  • 同事类(Colleague).

二. 具体实现

2.1 创建抽象中介者对象

    public abstract class AbstractMediator {
        private ColleagueA colleagueA;
        private ColleagueB colleagueB;
        public abstract void executeToA();
        public abstract void executeToB();
        public void setColleagueA(ColleagueA colleagueA) {
            this.colleagueA = colleagueA;
        }
        public void setColleagueB(ColleagueB colleagueB) {
            this.colleagueB = colleagueB;
        }
    }

2.2 创建具体中介者对象

    public class Mediator extends AbstractMediator {
        public void executeToA() {
            System.out.println("Mediator executeToA ...");
        }
        public void executeToB() {
            System.out.println("Mediator executeToB ...");
        }
    }

2.3 创建同事类

    public class ColleagueA {
        private AbstractMediator mediator;
        public ColleagueA(AbstractMediator mediator){
            this.mediator = mediator;
        }
        public void print(){
            System.out.println("ColleagueA print ... ");
            mediator.executeToB();
        }
    }
    public class ColleagueB {
        private AbstractMediator mediator;
        public ColleagueB(AbstractMediator mediator){
            this.mediator = mediator;
        }
        public void print(){
            System.out.println("ColleagueB print ...");
            mediator.executeToA();
        }
    }

2.4 调用

    public static void main(String[] args) {
        AbstractMediator mediator = new Mediator();
        ColleagueA colleagueA = new ColleagueA(mediator);
        ColleagueB colleagueB = new ColleagueB(mediator);
        mediator.setColleagueA(colleagueA);
        mediator.setColleagueB(colleagueB);
        colleagueA.print();
        colleagueB.print();
    }

2.5 输出

    ColleagueA print ... 
    Mediator executeToB ...
    ColleagueB print ...
    Mediator executeToA ...

三. 优缺点

3.1 优点

  • 各个同事类之间的解耦.
  • 降低类的复杂度.

3.2 缺点

  • 同事类过多会使中介者庞大,难以维护.

四. 源码

    https://github.com/Seasons20/DisignPattern.git

END

    原文作者:设计模式
    原文地址: https://segmentfault.com/a/1190000015171007
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞