您的位置:首页 > 编程语言 > Python开发

python设计模式之责任链

2017-09-09 17:05 127 查看

python设计模式之责任链

意图

使多个对象都有机会处理请求,从而避免请求的发送则和接受者之间的耦合关系。将这些对象连城一条链,并沿着这条连传递该请求,知道有一个对象处理它为止

适用性

有多个对象可以处理一个请求,哪个对象处理该请求运行时刻决定

想在不明确指定接受者的情况下,向多个对象中的一个提交一个请求

例子

# -*- coding=utf-8 -*-

class Handler(object):
def successor(self, successor):
self.successor = successor

class ConcreteHandler1(Handler):
def handle(self, request):
if request > 0 and request <= 10:
print("in handler1")
else:
self.successor.handle(request)

class ConcreteHandler2(Handler):
def handle(self, request):
if request > 10 and request <= 20:
print("in handler2")
else:
self.successor.handle(request)

class ConcreteHandler3(Handler):
def handle(self, request):
if request > 20 and request <= 30:
print("in handler3")
else:
print('end of chain, no handler for {}'.format(request))

if __name__ == "__main__":
h1 = ConcreteHandler1()
h2 = ConcreteHandler2()
h3 = ConcreteHandler3()

h1.successor(h2)
h2.successor(h3)

requests = [2, 5, 14, 22, 18, 3, 35, 27, 20]
for request in requests:
h1.handle(request)

#输出
in handler1
in handler1
in handler2
in handler3
in handler2
in handler1
end of chain, no handler for 35
in handler3
in handler2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 设计模式