写在前面
迪米特法则
只与你的直接朋友交谈,不跟“陌生人”说话。其含义是:如果两个软件实体无需直接通信,那么就不应当发生直接的相互调用,可以通过第三方转发该调用。其目的是降低类之间的耦合性,提高模块直接的相对独立性。
【行为型】中介者模式 Mediator (调停模式)
中介者模式定义:定义一个中介对象来封装一系列对象的交互,是原有对象之间的耦合松散,且可以独立的改变他们之间的交互。中介者模式又叫调停模式
如果说应用的话,一个典型的例子:消息队列。没错大名鼎鼎的 消息队列 就是典型的中介者模式
模式结构
- 抽象中介者 Mediator
- 具体中介者 Concrete Mediator
- 抽象同事类 Colleague
- 具体同事类 Concrete Colleague
上面提到的模式结构可能有些抽象,具体点来说就是每个同事类之间的 联系 或者相互间的 通信 都不是直接进行通信,而是通过中介者来转发处理,中介者模式 又称为 调停者模式,可以理解为 调停各个类之间的协作和通信。
那么 中介者模式 是属于 行为型模式 的 ,这里回顾一下 行为型模式 的定义:用于描述类或者对象之间如何进行相互协作,进而完成单个类无法完成的任务,或者定义怎样分配职责。
值得一提的问题
常常我们会将 外观/门面模式 Facade (结构型模式) 和 中介者 Mediator 放到一起谈,更有些时候甚至觉得他们好像傻傻分不清,好像都是搞了一个中间代理来提供服务呢?
其实区别还是比较明显的,首先记住一点 Mediator 对于所有的同事类都是平级一视同仁的,其处理的是同事类之间的复杂交互关系,类似于星状结构。而 Facade 不同,其是将子系统进行聚合来提供统一的服务来暴露给外部,类似于伞状结构,做服务端开发的同学应该都比较熟悉 Dao Service 这样的分层,整个时候 多个 Dao 就相当于子系统,而 Service 就是 Facade 门面,来聚合功能为更上层的 Controller 来提供统一服务。啊其实设计模式一直在我们身边!
实现案例
那么到了 show me the code 阶段
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import java.util.List;
/**
* @program: dying-stranded
* @description: 中介者模式 行为型
* @author: wangzibin
**/
public class MediatorDemo {
static abstract class Mediator {
public abstract void register(Client client);
public abstract void sendMessage(Client sender, String msg);
}
static class AllSendMediator extends Mediator {
private static final List<Client> clientList = Lists.newArrayList();
@Override
public void register(Client client) {
clientList.add(client);
client.mediator = this;
if (StringUtils.isBlank(client.name)) {
client.name = "客户端:" + System.currentTimeMillis();
}
}
@Override
public void sendMessage(Client sender, String msg) {
for (Client client : clientList) {
if (client != sender) {
client.receive(sender, msg);
}
}
}
}
static abstract class Client {
protected Mediator mediator;
protected String name;
public abstract void send(String msg);
public abstract void receive(Client sender, String msg);
}
static class SimpleClient extends Client {
@Override
public void send(String msg) {
mediator.sendMessage(this, msg);
}
@Override
public void receive(Client sender, String msg) {
System.out.println(sender.name + " 发送给你 " + this.name + ":" + msg);
}
}
public static void main(String[] args) {
Mediator mediator = new AllSendMediator();
Client clientA=new SimpleClient();
Client clientB=new SimpleClient();
Client clientC=new SimpleClient();
clientA.name="clientA";
clientB.name="clientB";
clientC.name="clientC";
mediator.register(clientA);
mediator.register(clientB);
mediator.register(clientC);
clientA.send("我发布了一篇博文【【行为型】中介者模式 Mediator (调停模式)】点击查看");
clientC.send("我发布了一篇博文【巴拉巴拉】点击查看");
}
}
为了方便展示我就写在一个类里了,大家在实际开发的过程中可以进行拆分,活学活用。
简单讲解一下:
有没有很像订阅?本质如此罢了。
我是 dying 搁浅,希望本文对你有所帮助,我们下期再见~