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设计模式编程中Adapter适配器模式的使用实例
- 简介Python设计模式中的代理模式与模板方法模式编程
- python设计模式-单例模式
- python设计模式
- python_设计模式——责任链模式
- 设计模式-策略模式-strategy-python
- Python设计模式系列之三: 创建型Factory Method模式
- Selenium+Python :WebDriver设计模式( Page Object )
- Python设计模式之观察者模式实例
- Python设计模式之工厂模式
- 设计模式之-抽象工厂模式VS简单工厂模式(python)
- 设计模式-结构型模式,python桥接模式
- Python案例-开发之路-设计模式-单例模式
- Python3 设计模式_工厂模式
- [Design Pattern]Python设计模式——设计原则
- 设计模式(11):责任连模式
- Python的设计模式编程入门指南
- 23种设计模式之python实现--State模式
- python设计模式之设计模式简介
- python设计模式(建造者模式)