Allows multiple objects to have the opportunity to process the request, thereby avoiding the coupling between the sender and receiver of the request. These objects are connected into a chain, and the request is passed along this chain until an object handles it
Object
Abstract handler (Handler)
Concrete handler (ConcreteHandler)
Client
Applicable scene
There are multiple objects that can handle a request, and which object handles is determined by the runtime
Submit a request to one of multiple objects without knowing the recipient
example
# 假设你需要进行请假,每一级主管都有自己的权限,项目主管三天以内,部门经理5天以内,总经理十天以内from abc import ABCMeta, abstractmethod
classHandler(metaclass=ABCMeta):
@abstractmethod
defhandle_leave(self):passclassGeneralManager(Handler):defhandle_leave(self, day):if day <=10:print(f"总经理准假{day}天")returnprint("你还是辞职吧")returnclassDeparmentManager(Handler):def__init__(self):
self.next= GeneralManager()defhandle_leave(self, day):if day <=5:print(f"总经理准假{day}天")returnprint("部门经理职权不足")return self.next.handle_leave(day)classProjectManager(Handler):def__init__(self):
self.next= DeparmentManager()defhandle_leave(self, day):if day <=3:print(f"项目主管准假{day}天")returnprint("项目主管职权不足")return self.next.handle_leave(day)
day =11
project_manager = ProjectManager()
project_manager.handle_leave(day)
advantage
Reduce the degree of coupling, an object does not need to know which other object processed its request