首页 > 代码库 > 责任链模式
责任链模式
模式说明
避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止,这就是职责链模式。
模式结构图
程序示例
说明:处理请假条,不同职位的领导处理不同天数的假条
代码:
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
责任链模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。