The chain of responsibility model , Connect multiple processing methods into a chain , Requests will flow along the chain until a node in the chain can handle the request . Usually, this chain is formed by an object containing a reference to another object , Each node has a condition for the request , When the condition is not met, it will be passed to the next node for processing .
The responsibility chain model has several key points :
Entity role :
import abc
# Abstract processor
class Handler(metaclass=abc.ABCMeta):
@abc.abstractmethod
def handle(self, day):
pass
# Specific handler , As one of the chain nodes .
class GeneralManager(Handler):
def handle(self, day):
if day <= 10:
print(f" The general manager granted leave {
day} God ")
else:
print(" Too long vacation , No leave !")
# Specific handler , As one of the chain nodes .
class DivisionManager(Handler):
def __init__(self):
self.next = GeneralManager() # Link to the next level
def handle(self, day):
if day <= 5:
print(f" The Department Manager granted leave {
day} God ")
else:
print(" Department managers are not qualified for leave ")
self.next.handle(day)
# Specific handler , As one of the chain nodes .
class ProjectManager(Handler):
def __init__(self):
self.next = DivisionManager() # Link to the next level
def handle(self, day):
if day <= 3:
print(f" The project manager granted leave {
day} God ")
else:
print(" The project manager is not qualified for leave ")
self.next.handle(day)
if __name__ == "__main__":
handler = ProjectManager()
handler.handle(4)