源码地址:https://github.com/weilanhanf/PythonDesignPatterns
说明:
当你作为一名coder已经快三十却还还没有女朋友,家中父母已经着急万分,此时要求你回家相亲,你嘴上说不要,我还年轻,还要为事业打拼,但是摸着头顶上日渐稀少的毛发,身体也很诚实,早早的写好了假条。此时要找领导请假,但是又不知道找哪个靠谱的领导。简言之,提交请求的对象并不明确知道谁是最终响应请求的对象。这样的话就存在了两种可能解决,广播的方式进行搜索命令对象还是让每个命令对象都指定某个处理对象。前者存在不确定性,后者则会造成处理对象之间的强耦合。
如果应用责任链模式解决问题是,你若想要请3天以内(包括3天的假),只需要直属经理批准就可以了;如果想请3-7天,不仅需要直属经理批准,部门经理需要最终批准;如果请假大于7天,不光要前两个经理批准,也需要总经理最终批准。“假条”在三个经理间是单向传递关系,像一条链条一样,因而,我们可以用一条“链”把他们进行有序连接。
责任链模式的定义如下:使多个对象都有机会处理请求,从而避免发送者和接收者的耦合关系。将对象连成链并沿着这条链传递请求直到被处理。
结构:
抽象处理者,具体处理者。
实例:
根据上述说明中的请假实例
#构造抽象经理类和各个层级的经理类: class manager(): successor = None name = '' def __init__(self, name): self.name = name def setSuccessor(self, successor): self.successor = successor def handleRequest(self, request): pass class lineManager(manager): def handleRequest(self, request): if request.requestType == 'DaysOff' and request.number <= 3: print('%s:%s Num:%d Accepted OVER' % (self.name, request.requestContent, request.number)) else: print('%s:%s Num:%d Accepted CONTINUE' % (self.name, request.requestContent, request.number)) if self.successor != None: self.successor.handleRequest(request) class departmentManager(manager): def handleRequest(self, request): if request.requestType == 'DaysOff' and request.number <= 7: print('%s:%s Num:%d Accepted OVER' % (self.name, request.requestContent, request.number)) else: print('%s:%s Num:%d Accepted CONTINUE' % (self.name, request.requestContent, request.number)) if self.successor != None: self.successor.handleRequest(request) class generalManager(manager): def handleRequest(self, request): if request.requestType == 'DaysOff': print('%s:%s Num:%d Accepted OVER' % (self.name, request.requestContent, request.number)) class request(): requestType = '' requestContent = '' number = 0 #request类封装了假期请求。在具体的经理类中,可以通过setSuccessor接口来构建“责任链”,并在handleRequest接口中实现逻辑。 # 场景类中实现如下 if __name__=="__main__": line_manager = lineManager('LINE MANAGER') department_manager = departmentManager('DEPARTMENT MANAGER') general_manager = generalManager('GENERAL MANAGER') line_manager.setSuccessor(department_manager) department_manager.setSuccessor(general_manager) req = request() req.requestType = 'DaysOff' req.requestContent = 'Ask 1 day off' req.number = 1 line_manager.handleRequest(req) req.requestType = 'DaysOff' req.requestContent = 'Ask 5 days off' req.number = 5 line_manager.handleRequest(req) req.requestType = 'DaysOff' req.requestContent = 'Ask 10 days off' req.number = 10 line_manager.handleRequest(req)
打印结果:
LINE MANAGER:Ask 1 day off Num:1 Accepted OVER
LINE MANAGER:Ask 5 days off Num:5 Accepted CONTINUE
DEPARTMENT MANAGER:Ask 5 days off Num:5 Accepted OVER
LINE MANAGER:Ask 10 days off Num:10 Accepted CONTINUE
DEPARTMENT MANAGER:Ask 10 days off Num:10 Accepted CONTINUE
GENERAL MANAGER:Ask 10 days off Num:10 Accepted OVER
优点:
降低了请求发出者和请求处理者之间的耦合。增强了对象指派职责的灵活性。
缺点:
一方面责任链过长会出现性能问题,另一方面,如果一个情求没有被正确处理也就是说不存在一个可以处理该请求的命令接收者而反复执行。
适用环境:
有多个对象可以处理一个请求,那个对象处理该请求会在运行时刻自动确定。若一个请求可能由一个对请求有链式优先级的处理群所处理时,可以考虑责任链模式。