行为模式-责任链模式

 责任链模式的内容:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链并沿着这条链传递该请求,直到有一个对象处理它为止。责任链的角色有抽象处理者、具体处理者和客户端。


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)
 

 使用场景:有多个对象可以处理一个请求,哪个对象处理由运行时决定;在不明确接收者的情况下,向多个对象中的一个提交一个请求。优点是降低耦合度,一个对象无需知道是其它哪一个对象处理其请求。

posted @ 2020-09-10 21:58  第十一个程序员  阅读(182)  评论(0编辑  收藏  举报