设计模式--中介者模式(调停者模式)

2021/12/15 23:40:24

本文主要是介绍设计模式--中介者模式(调停者模式),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 作用:当复杂功能应用之间重复调用时,在中间添加一层中介者包装服务,对外提供简单、通用和易扩展的服务能力。比如“联合国” 就是中介者,各个国家可以通过“联合国”通信。

接下来看代码:

模拟人之间沟通,通过中介。

1. 抽象中介者类

public abstract class Mediator {
    abstract void send(String message , Colleague colleague);
}

 2. 抽象同事类

public abstract class Colleague {

    protected Mediator mediator;

    public Colleague(Mediator mediator){
        this.mediator  = mediator;
    }

    abstract void send(String message);
}

3. 具体中介者类

public class ConcreteMediator extends Mediator{

    private ConcreteColleague1 concreteColleague1;
    private ConcreteColleague2 concreteColleague2;

    public ConcreteMediator setConcreteColleague1(ConcreteColleague1 concreteColleague1) {
        this.concreteColleague1 = concreteColleague1;
        return this;
    }

    public ConcreteMediator setConcreteColleague2(ConcreteColleague2 concreteColleague2) {
        this.concreteColleague2 = concreteColleague2;
        return this;
    }

    @Override
    public void send(String message, Colleague colleague) {
        if(colleague == concreteColleague1) {
            concreteColleague2.notify(message);
        }else {
            concreteColleague1.notify(message);
        }
    }
}

4. 同事实现类

public class ConcreteColleague1 extends Colleague{


    public ConcreteColleague1(Mediator mediator) {
        super(mediator);
    }

    @Override
    public void send(String message) {
        mediator.send(message,this);

    }

    public void notify(String message){
        System.out.println("NO1 message: " + message);
    }
}


public class ConcreteColleague2 extends Colleague{
    public ConcreteColleague2(Mediator mediator) {
        super(mediator);
    }

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

    public void notify(String message){
        System.out.println("NO2 message:" + message);
    }
}

5. 测试类

public class Test {
    public static void main(String[] args) {
        ConcreteMediator concreteMediator = new ConcreteMediator();
        ConcreteColleague1 concreteColleague1  = new ConcreteColleague1(concreteMediator);
        ConcreteColleague2 concreteColleague2 = new ConcreteColleague2(concreteMediator);

        concreteMediator.setConcreteColleague1(concreteColleague1);
        concreteMediator.setConcreteColleague2(concreteColleague2);

        concreteColleague1.send("你好!!!!");

        concreteColleague2.send("好的。。。");
    }
}

/****

> Task :Test.main()
NO2 message:你好!!!!
NO1 message: 好的。。。


***/

 减少了同事之间的耦合度。。。



这篇关于设计模式--中介者模式(调停者模式)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程