设计模式学习笔记(21)——中介者模式

版权声明:本文为博主原创,未经博主允许不得转载。 https://blog.csdn.net/weixin_36904568/article/details/90084668

1. 定义

又叫调停者模式。中介者包含了整个系统的控制逻辑,包装了对象之间相互作用的方式,使得这些对象(同事)不必相互明显引用。当这些对象中的某些对象之间的相互作用发生改变时,不会立即影响到其他对象(同事)之间的相互作用。从而保证这些相互作用可以彼此独立地变化。

2. 使用

  • 抽象中介者:定义出连接同事对象的接口和业务方法
  • 具体中介者:连接所有的具体同事类,并负责协调各同事对象的交互关系。
  • 抽象同事类:定义出连接中介者的接口
  • 具体同事类:实现自己的业务,在需要与其他同事通信的时候,与中介者通信
package MediatorPattern;

/**
 * 抽象中介者
 */
public interface Mediator {

    //中介者业务
    public void changed(Colleague colleague);

}

package MediatorPattern;

/**
 * 具体中介者
 */
public class ConcreteMediator implements Mediator {

    private ColleagueA a;

    private ColleagueB b;

    public void setA(ColleagueA a) {
        this.a = a;
    }

    public void setB(ColleagueB b) {
        this.b = b;
    }

    @Override
    public void changed(Colleague colleague) {
        if (colleague instanceof ColleagueA){
            b.receive();
        }
        else if (colleague instanceof ColleagueB){
            a.receive();
        }
    }
}

package MediatorPattern;

/**
 * 抽象同事
 */
public abstract class Colleague {

    private Mediator mediator;

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

    public Mediator getMediator() {
        return mediator;
    }
}

package MediatorPattern;

/**
 * 具体同事
 */
public class ColleagueA extends Colleague {

    private String name;

    public ColleagueA(Mediator mediator,String name) {
        super(mediator);
        this.name = name;
    }

    public void send() {
        System.out.println(this+"请求数据");
        getMediator().changed(this);
    }

    public void receive(){
        System.out.println(this+"收到数据");
    }

    @Override
    public String toString() {
        return "ColleagueA{" +
                "name='" + name + '\'' +
                '}';
    }
}

package MediatorPattern;

/**
 * 具体同事
 */
public class ColleagueB extends Colleague {

    private String name;

    public ColleagueB(Mediator mediator,String name) {
        super(mediator);
        this.name = name;
    }

    public void send() {
        System.out.println(this+"请求数据");
        getMediator().changed(this);
    }

    public void receive(){
        System.out.println(this+"收到数据");
    }

    @Override
    public String toString() {
        return "ColleagueB{" +
                "name='" + name + '\'' +
                '}';
    }
}

package MediatorPattern;

public class Test {
    public static void main(String[] args) {
        ConcreteMediator mediator = new ConcreteMediator();
        ColleagueA a = new ColleagueA(mediator,"A");
        ColleagueB b = new ColleagueB(mediator,"B");
        mediator.setA(a);
        mediator.setB(b);
        a.send();
        b.send();
    }
}

3. 特点

  • 将对象解耦,增加复用性
  • 集中控制逻辑
  • 减少对象之间的消息传递
  • 中介者可能过于复杂

猜你喜欢

转载自blog.csdn.net/weixin_36904568/article/details/90084668