目录
前言
在类设计中,一个类的功能实现可能还依赖其它类,甚至存在两个类之间互相依赖,你中有我,我中有你。表现在代码中就是类往往直接持有另外一个类的引用,类与类之间严重耦合,一个类的修改可能会影响到其他的类,不好维护。
中介者模式即是将对象之间的交互逻辑抽取出来,通过中介者来管理,使得对象之间无需直接引用,降低对象之间的耦合。集中管理交互逻辑相对更加容易维护。
相较于观察者模式,中介者中的对象能够实现相互通信,而观察者只能单方面接受被观察者的通知。
UML
plantuml
@startuml 'https://plantuml.com/class-diagram interface Colleague { + send(Object, String) : void + receiver(Object) : void } class ColleagueA { + send(Object, String) : void + receiver(Object) : void } class ColleagueB { + send(Object, String) : void + receiver(Object) : void } interface Mediator { + send(Object, String) : void + register(Colleague) : void } class ConcreteMediator { - colleagues : List<Colleague> + send(Object, String) : void + register(Colleague) : void } Colleague <|.. ColleagueA Colleague <|.. ColleagueB Mediator <|.. ConcreteMediator ConcreteMediator "1" --> "n" Colleague @enduml
类图
实战代码
模板
Colleague
java
public interface Colleague {
void send(Object object, String receiver);
void receive(Object object);
}
public class ColleagueA implements Colleague {
private String name;
private Mediator mediator;
public ColleagueA(String name, Mediator mediator) {
this.name = name;
this.mediator = mediator;
}
@Override
public void send(Object object, String receiver) {
mediator.send(object, receiver);
}
@Override
public void receive(Object object) {
System.out.println("A" + object);
}
}
public class ColleagueB implements Colleague {
private String name;
private Mediator mediator;
public ColleagueB(String name, Mediator mediator) {
this.name = name;
this.mediator = mediator;
}
@Override
public void send(Object object, String receiver) {
mediator.send(object, receiver);
}
@Override
public void receive(Object object) {
System.out.println("B" + object);
}
}
Mediator
java
public interface Mediator {
void send(Object object, String receiver);
void register(Colleague colleague);
}
public class ConcreteMediator implements Mediator {
private List<Colleague> colleagues = new ArrayList<>();
@Override
public void send(Object object, String receiver) {
for (Colleague colleague : colleagues) {
if (colleague.getName().equals(receiver)) {
colleague.receive(object);
}
}
}
@Override
public void register(Colleague colleague) {
colleagues.add(colleague);
}
}
Client
java
public class Client {
public static void main(String[] args) {
// 创建中介者
Mediator mediator = new ConcreteMediator();
// 创建节点并注册到中介者
ColleagueA colleagueA = new ColleagueA("A", mediator);
ColleagueB colleagueB = new ColleagueB("B", mediator);
mediator.register(colleagueA);
mediator.register(colleagueB);
colleagueA.send("Hello", "B");
}
}
中间件
中介者模式的思想在系统架构同样也适用
spring cloud gateway 就是一个中介者,服务间通信都是通过 gateway 来实现
消息队列也是一个中介者