我正在探索 python 中的不同概念,并且碰巧阅读了一个可用于责任链设计模式的协程示例。我写了以下代码:
from functools import wraps
def coroutine(function):
@wraps(function)
def wrapper(*args, **kwargs):
generator = function(*args, **kwargs)
next(generator)
return generator
return wrapper
@coroutine
def PlatinumCustomer(successor=None):
cust = (yield)
if cust.custtype == 'platinum':
print "Platinum Customer"
elif successor is not None:
successor.send(cust)
@coroutine
def GoldCustomer(successor=None):
cust = (yield)
if cust.custtype == 'gold':
print "Gold Customer"
elif successor is not None:
successor.send(cust)
@coroutine
def SilverCustomer(successor=None):
cust = (yield)
if cust.custtype == 'silver':
print "Silver Customer"
elif successor is not None:
successor.send(cust)
@coroutine
def DiamondCustomer(successor=None):
cust = (yield)
if cust.custtype == 'diamond':
print "Diamond Customer"
elif successor is not None:
successor.send(cust)
class Customer:
pipeline = PlatinumCustomer(GoldCustomer(SilverCustomer(DiamondCustomer())))
def __init__(self,custtype):
self.custtype = custtype
def HandleCustomer(self):
try:
self.pipeline.send(self)
except StopIteration:
pass
if __name__ == '__main__':
platinum = Customer('platinum')
gold = Customer('gold')
silver = Customer('silver')
diamond = Customer('diamond')
undefined = Customer('undefined')
platinum.HandleCustomer()
gold.HandleCustomer()
undefined.HandleCustomer()
我在这里尝试做的是尝试创建一个责任链模式解决方案来处理不同类型的客户(白金、黄金、钻石、白银)。
因为那个客户有一个管道,我已经提到了处理不同客户的顺序。Customer().HandleCustomer 将通过管道发送一个自身的实例,该管道将检查其 custtype 是否匹配,然后进行相应处理,或者将其发送给其继任者(如果可用)
问题:问题是当我运行上面的脚本时,它将处理第一个白金客户,而不是黄金或未定义的客户。我假设这是因为他已经到了发电机的尽头。如何修改代码,以便每次它是客户的新实例时,它都会从一开始就通过管道?