行為模式-責任鏈模式
阿新 • • 發佈:2020-09-10
責任鏈模式的內容:使多個物件都有機會處理請求,從而避免請求的傳送者和接收者之間的耦合關係。將這些物件連成一條鏈並沿著這條鏈傳遞該請求,直到有一個物件處理它為止。責任鏈的角色有抽象處理者、具體處理者和客戶端。
from abc import ABCMeta, abstractmethod
# 抽象處理著
class Handler(metaclass=ABCMeta):
@abstractmethod
def handle_leave(self, day):
pass
# 具體處理者
class GeneraManger(Handler):
def handle_leave(self, day):if day <= 10:
print('總經理准假%d' % day)
else:
print("get out")
# 具體的處理者
class DepartmentManger(Handler):
def __init__(self):
self.next = GeneraManger()
def handle_leave(self, day):
if day > 3 and day < 10:
print('部門經理准假%d' % day)
else:self.next.handle_leave(day)
class PerjectManger(Handler):
def __init__(self):
self.next = DepartmentManger()
def handle_leave(self, day):
if day <= 3:
print('專案經理准假%d' % day)
else:
self.next.handle_leave(day)
# 客戶端,高層程式碼
PerjectManger().handle_leave(5)
使用場景:有多個物件可以處理一個請求,哪個物件處理由執行時決定;在不明確接收者的情況下,向多個物件中的一個提交一個請求。優點是降低耦合度,一個物件無需知道是其它哪一個物件處理其請求。