You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
3.6 KiB

8 months ago
'''
职责链模式Chain of Responsibility Pattern
一种行为设计模式它允许你将请求沿着处理者链进行发送
收到请求后每个处理者均可对请求进行处理或将其传递给链上的下个处理者
在书城的业务背景中可以想象有这样的场景
客户下了一个订单该订单需要经历多个处理步骤比如验证库存计算价格生成发货通知等
这些处理步骤按照一定的顺序组织成一个处理链
'''
class Order:
def __init__(self, book_id, quantity):
self.book_id = book_id
self.quantity = quantity
class Handler:
def __init__(self, successor=None):
self.successor = successor
def handle_request(self, order):
raise NotImplementedError("Subclasses must implement handle_request()")
def successor_handle_request(self, order):
if self.successor is not None:
return self.successor.handle_request(order)
class InventoryHandler(Handler):
def handle_request(self, order):
if check_inventory(order.book_id, order.quantity):
print("InventoryHandler: Inventory checked, enough stock.")
return self.successor_handle_request(order)
else:
print("InventoryHandler: Inventory check failed, not enough stock.")
return False
class PricingHandler(Handler):
def handle_request(self, order):
price = calculate_price(order.book_id, order.quantity)
print(f"PricingHandler: Price calculated, total: {price}")
return self.successor_handle_request(order)
class NotificationHandler(Handler):
def handle_request(self, order):
send_notification(order)
print("NotificationHandler: Notification sent to customer.")
# Since this is the end of the chain, no successor to call.
return True
# Dummy functions to simulate the bookstore logic
def check_inventory(book_id, quantity):
return True # Simulate enough stock
def calculate_price(book_id, quantity):
return 10.0 * quantity # Simulate a fixed price per book
def send_notification(order):
pass # Simulate sending a notification to the customer
# Setting up the Chain of Responsibility
inventory_handler = InventoryHandler()
pricing_handler = PricingHandler()
notification_handler = NotificationHandler()
inventory_handler.successor = pricing_handler
pricing_handler.successor = notification_handler
# Client code
order = Order(book_id="12345", quantity=2)
result = inventory_handler.handle_request(order)
if result:
print("Order processing completed successfully.")
else:
print("Order processing failed.")
'''
在这个例子中我们有一个Handler基类它定义了一个处理请求的基本框架
具体的处理逻辑则在子类InventoryHandlerPricingHandler和NotificationHandler中实现
这些子类形成了职责链通过successor引用链接在一起
客户下了一个订单后这个订单请求会从库存处理器InventoryHandler开始处理
如果库存足够请求将被传递给价格处理器PricingHandler来计算总价
然后价格处理器再将请求传递给通知处理器NotificationHandler
最后发送通知给客户
如果任何处理器无法处理请求例如库存不足处理将在那里终止并且返回相应的结果
这个模式的好处是可以很容易地改变处理的顺序或者增加/删除处理器而不需要修改已有的代码
'''