中介者模式是一种行为型设计模式,它通过一个中介对象来封装一系列的对象交互,从而降低对象间的耦合度。在中介者模式中,对象之间不再直接交互,而是通过中介者来间接交互。
模式结构
中介者模式的主要角色包括:
- Mediator(中介者): 维护一个对象列表,提供接口用于对象之间的通信。
- Colleague(同事类): 与中介者通信的类,可以是具体的同事类。
- Concrete Mediator(具体中介者): 实现中介者的接口,定义对象之间交互的规则。
- Concrete Colleague(具体同事类): 实现同事类的接口,具体实现与中介者的通信。
适用场景
- 当对象之间存在大量通信时,通过中介者可以将对象之间的通信数降低到最低。
- 当对象之间的关联复杂,通过中介者可以简化结构。
- 当不希望对象之间相互耦合时,通过中介者可以降低耦合度。
示例
以下是一个简单的中介者模式的示例:
class Mediator:
def __init__(self):
self.colleagues = []
def add_colleague(self, colleague):
self.colleagues.append(colleague)
def notify(self, sender, message):
for colleague in self.colleagues:
if colleague != sender:
colleague.receive(message)
class Colleague:
def __init__(self, mediator):
self.mediator = mediator
def send(self, message):
self.mediator.notify(self, message)
def receive(self, message):
pass
class ConcreteColleagueA(Colleague):
def receive(self, message):
print(f"Colleague A received: {message}")
class ConcreteColleagueB(Colleague):
def receive(self, message):
print(f"Colleague B received: {message}")
# 创建中介者
mediator = Mediator()
# 创建同事类
colleague_a = ConcreteColleagueA(mediator)
colleague_b = ConcreteColleagueB(mediator)
# 将同事类添加到中介者
mediator.add_colleague(colleague_a)
mediator.add_colleague(colleague_b)
# 同事类之间通信
colleague_a.send("Hello, Colleague B!")
colleague_b.send("Hello, Colleague A!")
扩展阅读
了解更多设计模式,请访问我们的设计模式教程页面。