首页 > 代码库 > 责任链模式

责任链模式

模式说明

避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止,这就是职责链模式。

模式结构图

程序示例

说明:处理请假条,不同职位的领导处理不同天数的假条

代码:

class LeaveRequest(object):    def __init__(self, num, name):        self._num = num        self._name=name    def getnum(self):        return self._num    def getname(self):        return self._nameclass Handler(object):    def SetNextHandler(self,handler):        self._nextHandler=handler        def HandleRequest(self,request):        passclass Instructor(Handler):    def HandleRequest(self, request):        if request.getnum()<=3:            print instructor handle %s\‘s leave request:%s % (request.getname(),request.getnum())        else:            self._nextHandler.HandleRequest(request)class DepartmentHead(Handler):    def HandleRequest(self, request):        if request.getnum()<=5:            print department head handle %s\‘s leave request:%s % (request.getname(),request.getnum())        else:            self._nextHandler.HandleRequest(request)class Dean(Handler):    def HandleRequest(self, request):        if request.getnum()<=10:            print Dean head handle %s\‘s leave request:%s % (request.getname(),request.getnum())        else:            self._nextHandler.HandleRequest(request)class President(Handler):    def HandleRequest(self, request):        if request.getnum()<=15:            print President head handle %s\‘s leave request:%s % (request.getname(),request.getnum())        else:            self._nextHandler.HandleRequest(request)if __name__==__main__:    president = President()    dean = Dean()    dean.SetNextHandler(president)    department = DepartmentHead()    department.SetNextHandler(dean)    instructor=Instructor()    instructor.SetNextHandler(department)    request = LeaveRequest(8,wang)    instructor.HandleRequest(request)    request = LeaveRequest(12,chen)    dean.HandleRequest(request)

运行结果:

参考来源:

http://www.cnblogs.com/chenssy/p/3679190.html

http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

http://www.cnblogs.com/Terrylee/archive/2006/07/17/334911.html

 

责任链模式