介绍
责任链模式是一种行为型设计模式,它允许多个对象以链式的形式依次处理请求,直到请求被处理或者无处理对象为止
实现方式
责任链模式由多个处理器组成,每个处理器都可以处理一种请求。如果当前处理器无法处理请求,它将把请求传递给下一个处理器,直到请求被处理或者没有处理器可以处理为止。
案例
假设我们正在开发一个电子商务平台,现在需要实现一个购物车功能。当用户添加商品到购物车中时,需要进行以下验证
我们可以使用责任链模式来实现这个购物车功能。首先定义一个处理器基类
- class CartValidator:
- ? ? def __init__(self, next_validator=None):
- ? ? ? ? self.next_validator = next_validator
-
- ? ? def validate(self, item):
- ? ? ? ? if self.next_validator:
- ? ? ? ? ? ? return self.next_validator.validate(item)
- ? ? ? ? return True
这个基类包含了一个next_validator属性,表示后继处理器,以及一个validate方法,用于验证商品是否合法。如果存在后继处理器,则将验证请求传递给后继处理器。
接下来,我们可以定义三个具体的验证处理器,分别验证商品是否存在、商品库存是否充足以及商品是否已经下架
- # 模拟
- is_product_exist = True ?# 判断商品是否存在
- is_product_stock_enough = True ?# 判断商品库存是否充足
- is_product_on_sale = True ?# 判断商品是否已经下架
- class ProductExistValidator(CartValidator):
- ? ? def validate(self, item):
- ? ? ? ? # 判断商品是否存在
- ? ? ? ? # if not is_product_exist(item):
- ? ? ? ? if not is_product_exist:
- ? ? ? ? ? ? print('商品不存在')
- ? ? ? ? ? ? return False
- ? ? ? ? return super().validate(item)
-
- class ProductStockValidator(CartValidator):
- ? ? def validate(self, item):
- ? ? ? ? # 判断商品库存是否充足
- ? ? ? ? # if not is_product_stock_enough(item):
- ? ? ? ? if not is_product_stock_enough:
- ? ? ? ? ? ? print('库存不足')
- ? ? ? ? ? ? return False
- ? ? ? ? return super().validate(item)
-
- class ProductStatusValidator(CartValidator):
- ? ? def validate(self, item):
- ? ? ? ? # 判断商品是否已经下架
- ? ? ? ? # if not is_product_on_sale(item):
- ? ? ? ? if not is_product_on_sale:
- ? ? ? ? ? ? print('商品已下架')
- ? ? ? ? ? ? return False
- ? ? ? ? return super().validate(item)
-
- product_validator_chain = ProductExistValidator(ProductStockValidator(ProductStatusValidator()))
-
- def add_to_cart(item):
- ? ? if product_validator_chain.validate(item):
- ? ? ? ? # 添加商品到购物车中
- ? ? ? ? # add_item_to_cart(item)
- ? ? ? ? print("添加成功", item)
- ? ? ? ? pass
- ? ? else:
- ? ? ? ? # 商品验证失败
- ? ? ? ? print("商品验证失败")
这三个处理器都继承自CartValidator类,并覆盖了validate方法,实现了具体的商品验证逻辑。如果商品验证通过,则调用super()
.validate(item)方法,将验证请求传递给下一个处理器。
最后,我们可以将这三个处理器组成一个责任链:
- product_validator_chain = ProductExistValidator(ProductStockValidator(ProductStatusValidator()))
测试
正常测试
- add_to_cart("IPhone14 pro")
输出结果
添加成功 IPhone14 pro
库存不足测试
- # 模拟库存不足
- is_product_stock_enough = False
- add_to_cart("IPhone14 pro")
输出结果
库存不足
商品验证失败
使用场景
多个对象需要处理同一种请求,但处理的顺序和方式不同。例如,一个在线商店需要对订单进行风险评估,评估过程包括多个步骤,如检查订单是否来自欺诈用户、检查收货地址是否存在风险等。每个步骤可以使用一个处理器来处理,这些处理器可以组成一个责任链,对订单进行逐步风险评估。
对象不知道该由哪个处理器处理请求,需要动态确定处理器。java中的web框架的过滤器,需要根据请求的URL来选择合适的处理器,处理器可以根据自身能力来决定是否能够处理请求。
动态扩展。在系统中需要动态添加或删除处理器,同时保证请求可以被正确处理。例如,一个安全检查系统需要根据系统的安全策略来动态添加或删除安全检查处理器,同时保证请求可以被正确处理。
到此这篇关于浅谈Python 责任链模式的文章就介绍到这了,更多相关Python 责任链模式内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!