点击上方”python宝典”,关注获取python全套视频,
技术文章第一时间送达!
责任链模式
1、内容
使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求
直到有一个对象处理它为止
2、角色
3、使用场景
4、优点
降低耦合度:一个对象无需知道是其他哪一个对象处理其请求
**5、缺点**6、代码示例
请假示例
from abc import ABCMeta, abstractmethod
#
class Handler(metaclass=ABCMeta):
@abstractmethod
def handle_leave(self, day):
pass
class GeneralManagerHandler(Handler):
def handle_leave(self, day):
if day 10:
print("总经理批准%d天假"%day)
else:
print("呵呵")
class DepartmentManagerHandler(Handler):
def __init__(self):
self.successor = GeneralManagerHandler() #责任链的后面的一个人
def handle_leave(self, day):
if day 7:
print("部门经理批准%d天假"%day)
else:
print("部门经理无权准假")
self.successor.handle_leave(day)
class ProjectDirectorHandler(Handler):
def __init__(self):
self.successor = DepartmentManagerHandler()
def handle_leave(self, day):
if day 3:
print("项目主管批准%d天假")
else:
print("项目主管无权准假")
self.successor.handle_leave(day)
day = 4
h = ProjectDirectorHandler()
h.handle_leave(day)
模仿js事件处理
#--高级例子--模仿js事件处理
# JavaScript中假如有三个嵌套的div,每个div绑定一个事件,就像冒泡一样,先找里面的,
# 如果里面有就是里面的事件,如果里面没有就找上一层的。以此类推
from abc import ABCMeta, abstractmethod
class Handler(metaclass=ABCMeta):
@abstractmethod
def add_event(self, func):
pass
@abstractmethod
def handle(self):
pass
class BodyHandler(Handler):
def __init__(self):
self.func = None
def add_event(self, func):
self.func = func
def handle(self):
if self.func:
return self.func()
else:
print("已到最后一级,无法处理")
class ElementHandler(Handler):
def __init__(self, successor):
self.func = None
self.successor = successor
def add_event(self, func):
self.func = func
def handle(self):
if self.func:
return self.func()
else:
return self.successor.handle()
# 客户端
# bodydiva
body = {'type': 'body', 'name': 'body', 'children': [], 'father': None}
div = {'type': 'div', 'name': 'div', 'children': [], 'father': body}
a = {'type': 'a', 'name': 'a', 'children': [], 'father': div}
body['children'].append(div)
div['children'].append(a)
body['event_handler'] = BodyHandler()
div['event_handler'] = ElementHandler(div['father']['event_handler'])
a['event_handler'] = ElementHandler(a['father']['event_handler'])
def attach_event(element, func):
element['event_handler'].add_event(func)
#test
def func_div():
print("这是给div的函数")
def func_a():
print("这是给a的函数")
def func_body():
print("这是给body的函数")
# attach_event(div, func_div)
attach_event(a, func_a)
# attach_event(body, func_body)
a['event_handler'].handle()
识别图中二维码,欢迎关注python宝典