|
|
'''
|
|
|
中介者模式(Mediator Pattern)是一种行为型设计模式,它定义了一个中介对象来封装一系列对象之间的交互。
|
|
|
中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
|
|
|
|
|
|
设想书店管理系统,其中包含了多个组件,比如库存管理、订单处理、顾客管理等。
|
|
|
这些组件之间需要相互通信来协同工作。我们可以使用中介者模式来减少这些组件之间的直接依赖。
|
|
|
|
|
|
在这个示例中,BookstoreMediator 充当了中介者的角色,它协调了库存管理、订单处理和顾客管理之间的交互。
|
|
|
当某个事件发生时(比如顾客下订单),相应的组件会通过中介者发送通知,中介者再根据事件类型协调其他组件的响应。
|
|
|
'''
|
|
|
|
|
|
from abc import ABC, abstractmethod
|
|
|
|
|
|
#定义一个中介者接口和具体的中介者实现
|
|
|
|
|
|
# 中介者接口
|
|
|
class Mediator(ABC):
|
|
|
@abstractmethod
|
|
|
def notify(self, sender, event):
|
|
|
pass
|
|
|
|
|
|
# 具体的中介者实现
|
|
|
class BookstoreMediator(Mediator):
|
|
|
def __init__(self, inventory, order, customer):
|
|
|
self.inventory = inventory
|
|
|
self.order = order
|
|
|
self.customer = customer
|
|
|
|
|
|
def notify(self, sender, event):
|
|
|
if event == 'book_ordered':
|
|
|
print("BookstoreMediator: Order notification received. Checking inventory...")
|
|
|
if self.inventory.has_stock():
|
|
|
print("BookstoreMediator: Inventory has stock. Processing order...")
|
|
|
self.order.process_order()
|
|
|
self.customer.notify_order_success()
|
|
|
else:
|
|
|
print("BookstoreMediator: Inventory out of stock. Cancelling order...")
|
|
|
self.order.cancel_order()
|
|
|
self.customer.notify_order_failure()
|
|
|
# 可以添加更多的事件处理逻辑
|
|
|
|
|
|
# 库存管理组件
|
|
|
class Inventory:
|
|
|
def has_stock(self):
|
|
|
# 这里简化逻辑,直接返回有库存
|
|
|
return True
|
|
|
|
|
|
# 订单处理组件
|
|
|
class Order:
|
|
|
def process_order(self):
|
|
|
print("Order: Order is being processed...")
|
|
|
|
|
|
def cancel_order(self):
|
|
|
print("Order: Order is being cancelled...")
|
|
|
|
|
|
# 顾客管理组件
|
|
|
class Customer:
|
|
|
def notify_order_success(self):
|
|
|
print("Customer: Order successful. Notifying customer...")
|
|
|
|
|
|
def notify_order_failure(self):
|
|
|
print("Customer: Order failed. Notifying customer...")
|
|
|
|
|
|
# 组件之间的交互通过中介者进行
|
|
|
class BookstoreComponent:
|
|
|
def __init__(self, mediator):
|
|
|
self.mediator = mediator
|
|
|
|
|
|
def send_notification(self, event):
|
|
|
self.mediator.notify(self, event)
|
|
|
|
|
|
# 示例使用
|
|
|
if __name__ == "__main__":
|
|
|
# 创建组件
|
|
|
inventory = Inventory()
|
|
|
order = Order()
|
|
|
customer = Customer()
|
|
|
|
|
|
# 创建中介者并注入组件
|
|
|
mediator = BookstoreMediator(inventory, order, customer)
|
|
|
|
|
|
# 创建与中介者关联的书店组件(这里以订单为例)
|
|
|
order_component = BookstoreComponent(mediator)
|
|
|
|
|
|
# 触发事件(比如:下订单)
|
|
|
order_component.send_notification('book_ordered') |