重学设计模式之中介者模式

121 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第二十三天,点击查看活动详情

重学设计模式之中介者模式(Kotlin)

前言

中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护。中介者模式属于行为型模式

适用场景

  1. 系统中对象之间存在比较复杂的引用关系,导致它们之间的依赖关系结构混乱而且难以复用该对象

  2. 想通过一个中间类来封装多个类中的行为,而又不想生成太多的子类

中介者模式的角色以及职责

  • 中介者(Mediator):中介者是一个接口,该接口定义了用于同事(Colleague)对象之间进行通信的方法

  • 具体中介者(ConcreteMediator):具体中介者是实现中介者接口的类。具体中介者需要包含所有具体同事(ConcreteColleague)的引用,并通过实现中介者接口中的方法来满足具体同事之间的通信要求

  • 同事(Colleague) :一个接口,规定了具体同事需要实现的方法;

  • 具体同事(ConcreteColleague) :实现了同事接口的类。具体同事需要包含具体中介者的引用,一个具体同事需要和其他具体同事交互时,只需将自己的请求通知给它所包含的具体中介者的引用

src=http___upload-images.jianshu.io_upload_images_16537602-b5dec5a37fab407e.png&refer=http___upload-images.jianshu.webp

实例

  1. 创建同事抽象类
/**
 * 同事抽象类
 */
public abstract class Colleague {

    //中介者抽象类
    protected Mediator mediator;

    //接受消息
    public abstract void receive();

    //发送消息
    public abstract void send();

    public void setMediator(Mediator mediator) {
        this.mediator = mediator;
    }
}
  1. 创建中介者抽象类
/**
 * 中介者抽象类
 */
public abstract class Mediator {

    //注册同事
    abstract void register(Colleague colleague);

    //通知中介者,发送消息
    abstract void relay(Colleague colleague);

}
  1. 创建中介者实现类
/***
 * 中介者实现类
 */
public class ConcreteMediator implements Mediator {

    /**
     * 被中介者代理的同事
     */
    private List<Colleague> colleagues;

    public ConcreteMediator() {
        colleagues = new ArrayList<>();
    }

    public void register(Colleague colleague) {
        if (!colleagues.contains(colleague)) {
            colleague.setMediator(this);
            this.colleagues.add(colleague);
        }
    }

    public void relay(Colleague colleague) {
        colleagues.forEach(c -> {
            if (!c.equals(colleague)) {
                c.receive();
            }
        });
    }
}
  1. 创建具体的同事类2
/**
 * 具体的同事类2
 */
public class ConcreteColleague2 extends Colleague {
    @Override
    public void receive() {
        System.out.println("colleague2 receive message.");
    }

    @Override
    public void send() {
        System.out.println("colleague2 send message.");
        //请中介者转发
        this.mediator.relay(this);
    }
}
  1. 开始测试
/**
 * 测试与应用
 */
public class Test {

    public static void main(String[] args) {
        //构建中介者
        Mediator mediator = new ConcreteMediator();

        //构建具体的同事类
        Colleague colleague1 = new ConcreteColleague1();
        Colleague colleague2 = new ConcreteColleague2();

        //注册同事
        mediator.register(colleague1);
        mediator.register(colleague2);

        //发送消息
        colleague1.send();
        colleague2.send();
    }
}

输出:

```
colleague1 send message.
colleague2 receive message.
colleague2 send message.
colleague1 receive message.
```

中介者模式的优缺点

  • 优点

    1. 降低了类的复杂度,将一对多转化成了一对一
    2. 各个类之间的解耦。
  • 缺点

    1. 中介者会庞大,变得复杂难以维护