
设计模式之中介者模式
什么是中介者模式?
- 中介者模式是一种行为型设计模式,它的核心思想是用一个中介者对象来封装一组对象之间的交互,使对象之间不需要相互引用,从而降低耦合性。
中介者模式的核心概念
· 问题:
在复杂系统中,多个对象之间可能会直接通信,导致耦合度过高,维护起来十分困难。
· 解决方案:
通过引入中介者(Mediator),让对象不再直接通信,而是通过中介者协调它们的交互。
· 优点
- 降低对象间的耦合性,每个对象不需要知道其他对象的存在。
- 更容易维护和扩展,新增对象时不影响现有对象。
- 优化通信方式,避免对象间过度依赖。
· 缺点
- 中介者可能变得复杂,如果处理的对象过多,可能会变成“上帝类”,难以维护。
例子:飞机塔台控制
假设有多个飞机在机场起飞和降落,如果每架飞机都要直接和其他飞机通信,就会非常混乱。为了解决这个问题,我们引入塔台(中介者),让所有飞机通过塔台进行协调。
代码示例
1️⃣ 定义中介者接口
1 2 3 4 5 6 7 8 9 10
|
public interface AirTrafficControl { void sendMessage(String message, Airplane airplane); }
|
2️⃣ 具体中介者(塔台)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
public class ControlTower implements AirTrafficControl {
private final List<Airplane> airplanes = new ArrayList<>();
public void registerAirplane(Airplane airplane) { airplanes.add(airplane); }
@Override public void sendMessage(String message, Airplane sender) { airplanes.forEach(airplane -> { if (airplane != sender) { airplane.receiveMessage(message); } }); } }
|
3️⃣ 定义同事类(飞机)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
public abstract class Airplane {
protected AirTrafficControl controlTower;
public Airplane(AirTrafficControl controlTower) { this.controlTower = controlTower; }
public abstract void sendMessage(String message); public abstract void receiveMessage(String message); }
|
4️⃣ 具体飞机类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
public class Boeing737 extends Airplane { public Boeing737(AirTrafficControl controlTower) { super(controlTower); }
@Override public void sendMessage(String message) { System.out.println("Boeing737 发送消息:" + message); controlTower.sendMessage(message, this); }
@Override public void receiveMessage(String message) { System.out.println("Boeing737 收到消息:" + message); } }
public class AirbusA320 extends Airplane { public AirbusA320(AirTrafficControl controlTower) { super(controlTower); }
@Override public void sendMessage(String message) { System.out.println("AirbusA320 发送消息:" + message); controlTower.sendMessage(message, this); }
@Override public void receiveMessage(String message) { System.out.println("AirbusA320 收到消息:" + message); } }
|
5️⃣ 测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
public class MediatorPatternDemo { public static void main(String[] args) { ControlTower tower = new ControlTower();
Airplane plane1 = new Boeing737(tower); Airplane plane2 = new AirbusA320(tower);
tower.registerAirplane(plane1); tower.registerAirplane(plane2);
plane1.sendMessage("请求起飞🛫"); plane2.sendMessage("请求降落🛬"); } }
|
🛫 运行结果
1 2 3 4
| Boeing737 发送消息:请求起飞🛫 AirbusA320 收到消息:请求起飞🛫 AirbusA320 发送消息:请求降落🛬 Boeing737 收到消息:请求降落🛬
|
📌 适用场景
- GUI组件交互:按钮、输入框、复选框通过中介者协调,而不是直接调用。
- 聊天室:所有用户通过服务器(中介者)发送和接收消息。
- 任务调度系统:各个子系统不直接通信,而是通过任务调度中心协调。
📌 总结
- 核心思想:让多个对象通过中介者交互,而不是直接通信,降低耦合
- 优点:降低对象之间的依赖,提高代码的可维护性和扩展性。
- 缺点:中介者可能变得复杂,成为“上帝类“。
- 应用场景:GUI组件、聊天室、任务调度、飞机塔台、微服务通信等。
中介者模式通过一个中间对象来协调多个对象的交互,避免对象之间直接耦合,提升系统的可维护性和扩展性。