本文主要是介绍python 设计模式-责任链模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
责任链模式的关键在于请求会沿着责任链传播,直到处理成功。我们模拟OA上费用报销的流程,上代码:
from abc import ABCMeta, abstractmethodclass Role(metaclass=ABCMeta):def setNext(self, role):self._next_role = roledef getNext(self):return self._next_role@abstractmethoddef audit(self, reimbursement):passclass DepartmentManager(Role):def audit(self, reimbursement):if reimbursement < 500:print('approved by department manager')return Trueelse:self._next_role.audit(reimbursement)class DivisionManager(Role): def audit(self, reimbursement):if reimbursement < 2000:print('approved by division manager')return Trueelse:self._next_role.audit(reimbursement)class GeneralManager(Role):def audit(self, reimbursement):if reimbursement < 1000000:print('approved by general manager')return Trueelse:return Falseif __name__ == '__main__':gm = GeneralManager()dim = DivisionManager()dim.setNext(gm)dem = DepartmentManager()dem.setNext(dim)dem.audit(1000)
输出
approved by division manager
请求会从部门主管到部门经理,一直到总经理,如果中间处理成功则不再往后传播了。
这篇关于python 设计模式-责任链模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!