链模式chain,可以将一个处理流程串成一个链,每一环包括三部分:
1、初始化中,需要指向传入的类,
2、有判断调用传入类的method
3、有自己这一环需要做的处理 @abstractmethon
还有一个约束,应该是终止环(class),这一环仅有第三项,需要做的处理,表明没有找到合适的环。
代码示例:
class Handler(object): __metaclass__ = abc.ABCMeta def __init__(self, successor=None): self._successor = successor def handle(self, request): res = self._handle(request) if not res: self._successor.handle(request) @abc.abstractmethod def _handle(self, request): raise NotImplementedError('Must provide implementation in subclass.') class ConcreteHandler1(Handler): def _handle(self, request): if 0 < request <= 10: print('request {} handled in handler 1'.format(request)) return True class ConcreteHandler2(Handler): def _handle(self, request): if 10 < request <= 20: print('request {} handled in handler 2'.format(request)) return True class ConcreteHandler3(Handler): def _handle(self, request): if 20 < request <= 30: print('request {} handled in handler 3'.format(request)) return True class DefaultHandler(Handler): def _handle(self, request): print('end of chain, no handler for {}'.format(request)) return True class Client(object): def __init__(self): self.handler = ConcreteHandler1( ConcreteHandler3(ConcreteHandler2(DefaultHandler()))) def delegate(self, requests): for request in requests: self.handler.handle(request)
if __name__ == "__main__": client1 = Client() requests = [2, 5, 14, 22, 18, 3, 35, 27, 20] client1.delegate(requests)