设计模式之十三--职责链模式

【设计模式之十三--职责链模式】职责链模式:是多个对象都有机会处理请求,从而避免请求的法总这和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,知道有一个对象处理它为止。
这个模式在公司中非常常见,一个人请假,先从自己的leader开始,然后进一步到科长,总经理。职责链条非常清晰。

from abc import ABCMeta, abstractmethodclass Manager(metaclass=ABCMeta):def __init__(self, name): self.name = name self._supervisor = None@abstractmethod def set_supervisor(self, supervisor): pass@abstractmethod def handle_request(self, request): passclass Leader(Manager):def __init__(self, name): self.supervisor = None super().__init__(name)def set_supervisor(self, supervisor): self.supervisor = supervisordef handle_request(self, request): if request.request_type is "day_off" and request.number < 2: print("{0}:{1} number {2} is approved".format(self.name, request.request_content, request.number))else: if self.supervisor is not None: self.supervisor.handle_request(request)class SectionChief(Manager):def __init__(self, name): self.supervisor = None super().__init__(name)def set_supervisor(self, supervisor): self.supervisor = supervisordef handle_request(self, request): if request.request_type is "day_off" and request.number < 5: print("{0}:{1} number {2} is approved".format(self.name, request.request_content, request.number)) else: if self.supervisor is not None: self.supervisor.handle_request(request)class GeneralManager(Manager):def __init__(self, name): self.supervisor = None super().__init__(name)def set_supervisor(self, supervisor): self.supervisor = supervisordef handle_request(self, request): if request.request_type is "salary_increase" and request.number < 1000: print("{0}:{1} number {2} is approved".format(self.name, request.request_content, request.number)) else: print("{0}:{1} number {2} is not approved".format(self.name, request.request_content, request.number))class Request: def __init__(self): self.__request_type = None self.__request_content = None self.__number = None@property def request_type(self): return self.__request_type@request_type.setter def request_type(self, value): self.__request_type = value@property def request_content(self): return self.__request_content@request_content.setter def request_content(self, value): self.__request_content = value@property def number(self): return self.__number@number.setter def number(self, value): self.__number = valueif __name__ == "__main__": leader = Leader("Jordon") section_chief = SectionChief("Martin") general_manager = GeneralManager("Dell")leader.set_supervisor(section_chief) section_chief.set_supervisor(general_manager)request = Request() request.request_type = "day_off" request.request_content = "Li ask day off" request.number = 4 leader.handle_request(request)request = Request() request.request_type = "salary_increase" request.request_content = "Li ask for salary increase" request.number = 1200leader.handle_request(request)

    推荐阅读