# -*- coding:UTF-8 -*-import abcclass Handler(metaclass=abc.ABCMeta): def __init__(self): self._successor = None def set_successor(self, successor): self._successor = successor @abc.abstractmethod def handle_request(self, request): passclass ConcreteHandler1(Handler): def handle_request(self, request): if request >= 0 and request < 10: print("{}处理请求{}".format(self.__class__.__name__, request)) elif self._successor != None: self._successor.handle_request(request)class ConcreteHandler2(Handler): def handle_request(self, request): if request >= 10 and request < 20: print("{}处理请求{}".format(self.__class__.__name__, request)) elif self._successor is not None: self._successor.handle_request(request)class ConcreteHandler3(Handler): def handle_request(self, request): if request >= 20 and request < 30: print("{}处理请求{}".format(self.__class__.__name__, request)) elif self._successor is not None: self._successor.handle_request(request)if __name__ == "__main__": h1 = ConcreteHandler1() h2 = ConcreteHandler2() h3 = ConcreteHandler3() h1.set_successor(h2) h2.set_successor(h3) requests = [2, 5, 14, 22, 18, 3, 27, 20] for request in requests: h1.handle_request(request)