Python设计模式详解之17 —— 中介者模式

Mediator(中介者)设计模式 是一种行为型设计模式,用于通过一个中介对象封装一组对象之间的交互,简化复杂的对象之间的依赖关系。它的目标是减少对象之间的直接耦合,使系统更加灵活和可维护。

在 Python 中,Mediator 模式 通常通过一个专门的中介类管理多个组件的交互。这些组件通过中介者传递消息,而不是直接引用彼此。


Mediator 模式的组成

  1. Mediator(中介者接口)

    • 定义组件间通信的接口。
  2. ConcreteMediator(具体中介者)

    • 实现中介者接口,协调组件之间的交互。
  3. Colleague(同事类接口)

    • 定义组件的基本行为,组件通过中介者通信。
  4. 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)

适用场景

  1. 解耦对象之间的复杂依赖关系:组件之间相互依赖会导致代码难以维护,Mediator 模式将依赖转移到中介者。
  2. 集中控制交互逻辑:例如,管理 GUI 界面中多个组件的交互。
  3. 实现模块间松耦合:用于多人协作的系统、消息队列、聊天系统等。

优缺点

优点
  1. 降低耦合:同事类之间无需直接通信。
  2. 提高灵活性:更改交互逻辑只需修改中介者。
  3. 增强代码可读性和维护性:组件只需关注自己的功能。
缺点
  1. 中介者过于复杂:如果组件数量过多,中介者容易成为“上帝对象”。
  2. 调试难度增加:所有交互逻辑都集中在中介者,可能难以跟踪。

总结

Python 中的 Mediator 模式可以通过直接实现类或结合现有的事件系统(如 asynciosignals)灵活应用。合理的抽象与设计是避免中介者复杂化的关键。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拾工

雁过留声

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值