码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之责任链模式

时间:2018-05-02 02:59:47      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:需要   UNC   art   style   init   ret   handle   ...   and   

设计模式之责任链模式

 例一:

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()

 

设计模式之责任链模式

标签:需要   UNC   art   style   init   ret   handle   ...   and   

原文地址:https://www.cnblogs.com/aadmina/p/8977864.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!