Mediator(中介者)设计模式 是一种行为型设计模式,用于通过一个中介对象封装一组对象之间的交互,简化复杂的对象之间的依赖关系。它的目标是减少对象之间的直接耦合,使系统更加灵活和可维护。
在 Python 中,Mediator 模式 通常通过一个专门的中介类管理多个组件的交互。这些组件通过中介者传递消息,而不是直接引用彼此。
Mediator 模式的组成
-
Mediator(中介者接口):
- 定义组件间通信的接口。
-
ConcreteMediator(具体中介者):
- 实现中介者接口,协调组件之间的交互。
-
Colleague(同事类接口):
- 定义组件的基本行为,组件通过中介者通信。
-
ConcreteColleague(具体同事类):
- 实现具体功能,并通过中介者与其他组件交互。
如何在 Python 中实现 Mediator 模式
示例:聊天室系统
# 中介者接口
class Mediator:
def notify(self, sender, event):
raise NotImplementedError("Subclasses must implement this method.")
# 具体中介者
class ChatRoom(Mediator):
def __init__(self):
self.participants = {}
def register(self, participant):
self.participants[participant.name] = participant
participant.set_mediator(self)
def notify(self, sender, message):
for name, participant in self.participants.items():
if participant != sender: # 消息不发送给发送者
participant.receive(message)
# 同事类接口
class Participant:
def __init__(self, name):
self.name = name
self.mediator = None
def set_mediator(self, mediator):
self.mediator = mediator
def send(self, message):
print(f"{self.name} 发送消息: {message}")
if self.mediator:
self.mediator.notify(self, message)
def receive(self, message):
print(f"{self.name} 收到消息: {message}")
# 使用 Mediator 模式
if __name__ == "__main__":
# 创建具体中介者
chat_room = ChatRoom()
# 创建同事类
alice = Participant("Alice")
bob = Participant("Bob")
charlie = Participant("Charlie")
# 注册同事类到中介者
chat_room.register(alice)
chat_room.register(bob)
chat_room.register(charlie)
# 同事类通过中介者发送消息
alice.send("Hello, everyone!")
bob.send("Hi, Alice!")
charlie.send("Hey, folks!")
输出结果:
Alice 发送消息: Hello, everyone!
Bob 收到消息: Hello, everyone!
Charlie 收到消息: Hello, everyone!
Bob 发送消息: Hi, Alice!
Alice 收到消息: Hi, Alice!
Charlie 收到消息: Hi, Alice!
Charlie 发送消息: Hey, folks!
Alice 收到消息: Hey, folks!
Bob 收到消息: Hey, folks!
改进:解耦中介者与同事类
可以使用 Python 的 弱引用(weakref
) 或者事件系统(如 observer
模式)进一步解耦中介者和同事类。
示例:用弱引用存储同事类
from weakref import WeakSet
class ChatRoom(Mediator):
def __init__(self):
self.participants = WeakSet()
def register(self, participant):
self.participants.add(participant)
participant.set_mediator(self)
def notify(self, sender, message):
for participant in self.participants:
if participant != sender:
participant.receive(message)
适用场景
- 解耦对象之间的复杂依赖关系:组件之间相互依赖会导致代码难以维护,Mediator 模式将依赖转移到中介者。
- 集中控制交互逻辑:例如,管理 GUI 界面中多个组件的交互。
- 实现模块间松耦合:用于多人协作的系统、消息队列、聊天系统等。
优缺点
优点
- 降低耦合:同事类之间无需直接通信。
- 提高灵活性:更改交互逻辑只需修改中介者。
- 增强代码可读性和维护性:组件只需关注自己的功能。
缺点
- 中介者过于复杂:如果组件数量过多,中介者容易成为“上帝对象”。
- 调试难度增加:所有交互逻辑都集中在中介者,可能难以跟踪。
总结
Python 中的 Mediator 模式可以通过直接实现类或结合现有的事件系统(如 asyncio
、signals
)灵活应用。合理的抽象与设计是避免中介者复杂化的关键。