设计模式之责任链模式
例一:
from abc import ABCMeta,abstractmethod class BaseHandler(metaclass=ABCMeta): @abstractmethod def handle_leave(self,days): pass class GeneralManagerHandler(BaseHandler): def handle_leave(self,days): if days < 10: print('总经理批准%s天假期'%days) else: print('你想多了吧......') class DepartmentManagerHandler(BaseHandler): def __init__(self): self.leader = GeneralManagerHandler() def handle_leave(self,days): if days < 5: print('部门经理批准%s天假期'%days) else: print('部门经理无权配准%s天假,需要向总经理申请'%days) self.leader.handle_leave(days) class ProjectDirectorHandler(BaseHandler): def __init__(self): self.leader = DepartmentManagerHandler() def handle_leave(self,days): if days < 3: print('项目主管批准%s天假期'%days) else: print('项目主管无权配准%s天假,需要向部门经理经理申请' % days) self.leader.handle_leave(days) employee = ProjectDirectorHandler() employee.handle_leave(15)
例二:
from abc import ABCMeta,abstractmethod class BaseHandler(metaclass=ABCMeta): @abstractmethod def add_event(self,func): pass @abstractmethod def handle(self): pass class BodyHandler(BaseHandler): 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('ending......') class ElementHandler(BaseHandler): def __init__(self,leader): self.func = None self.leader = leader def add_event(self,func): self.func = func def handle(self): if self.func: return self.func() else: return self.leader.handle() body = {'type':'body','name':'body','children':[],'father':None,'event_handler':None} div = {'type':'div','name':'div','children':[],'father':body,'event_handler':None} span = {'type':'span','name':'span','children':[],'father':div,'event_handler':None} body['children'].append(div) div['children'].append(span) body['event_handler'] = BodyHandler() div['event_handler'] = ElementHandler(div['father']['event_handler']) span['event_handler'] = ElementHandler(span['father']['event_handler']) def bind_event(element,func): element['event_handler'].add_event(func) def func_body(): print('这是给body的函数') def func_div(): print('这是给div的函数') def func_span(): print('这是给span的函数') bind_event(body,func_body) # bind_event(div,func_div) # bind_event(span,func_span) span['event_handler'].handle() div['event_handler'].handle() body['event_handler'].handle()