跳转至

中介者模式

中介者模式

中介者模式(Mediator Pattern)是一种行为型设计模式,它用于减少对象之间的直接通信,从而降低耦合度。中介者模式通过引入一个中介对象来协调一组对象之间的交互,使对象不需要显式地相互引用,从而使其耦合松散,且可以独立地改变它们之间的交互。

中介者模式的特点

  1. 减少耦合:对象之间通过中介者对象进行通信,降低了对象之间的直接依赖和耦合。
  2. 集中控制:中介者对象可以集中控制和管理多个对象之间的交互。
  3. 复用性:可以灵活地重用和扩展对象,因为对象之间的交互被封装在中介者对象中。

中介者模式的结构

  1. 中介者接口(Mediator):定义了各个同事对象通信的接口方法。
  2. 具体中介者(Concrete Mediator):实现了中介者接口,负责协调各个同事对象的交互关系。
  3. 同事类(Colleague):每个同事对象都需要知道中介者对象,并通过中介者来进行交互。
  4. 具体同事类(Concrete Colleague):实现同事类接口,每个具体同事类都知道如何与其他同事对象进行通信,但不知道如何与中介者通信。

中介者模式的Python实现

以下是中介者模式在Python中的一个简单实现示例:

1. 定义中介者接口和具体中介者类

from abc import ABC, abstractmethod

# 中介者接口
class Mediator(ABC):
    @abstractmethod
    def send_message(self, colleague, message):
        pass

# 具体中介者类
class ConcreteMediator(Mediator):
    def __init__(self):
        self._colleague1 = None
        self._colleague2 = None

    def set_colleague1(self, colleague):
        self._colleague1 = colleague

    def set_colleague2(self, colleague):
        self._colleague2 = colleague

    def send_message(self, colleague, message):
        if colleague == self._colleague1:
            self._colleague2.receive_message(message)
        elif colleague == self._colleague2:
            self._colleague1.receive_message(message)

2. 定义同事类接口和具体同事类

# 同事类接口
class Colleague(ABC):
    def __init__(self, mediator):
        self._mediator = mediator

    @abstractmethod
    def send(self, message):
        pass

    @abstractmethod
    def receive_message(self, message):
        pass

# 具体同事类A
class ConcreteColleagueA(Colleague):
    def send(self, message):
        self._mediator.send_message(self, message)

    def receive_message(self, message):
        print(f"ConcreteColleagueA received: {message}")

# 具体同事类B
class ConcreteColleagueB(Colleague):
    def send(self, message):
        self._mediator.send_message(self, message)

    def receive_message(self, message):
        print(f"ConcreteColleagueB received: {message}")

3. 客户端代码

if __name__ == "__main__":
    mediator = ConcreteMediator()

    colleague1 = ConcreteColleagueA(mediator)
    colleague2 = ConcreteColleagueB(mediator)

    mediator.set_colleague1(colleague1)
    mediator.set_colleague2(colleague2)

    colleague1.send("Hello from Colleague A")
    colleague2.send("Hello from Colleague B")

运行结果

ConcreteColleagueB received: Hello from Colleague A
ConcreteColleagueA received: Hello from Colleague B

说明

  1. 中介者接口(Mediator):定义了同事对象通信的接口方法 send_message
  2. 具体中介者类(ConcreteMediator):实现了中介者接口,负责协调和管理同事对象之间的交互关系。
  3. 同事类接口(Colleague):定义了同事对象的基本行为,包括发送消息和接收消息的方法。
  4. 具体同事类(ConcreteColleagueA 和 ConcreteColleagueB):实现了同事类接口,每个具体同事类都知道如何与其他同事对象进行通信,并通过中介者来发送和接收消息。

中介者模式通过引入中介者对象,将对象之间复杂的交互关系进行封装,从而实现了对象之间的解耦和松散耦合。这种模式适用于对象之间的交互复杂、相互依赖程度高的情况,可以有效地减少对象之间的直接引用,提高系统的灵活性和可维护性。

评论