職責鏈模式:將能處理請求的對象連成一條鏈,並沿著這條鏈傳遞該請求,直到有一個對象處理請求為止,避免請求的寄件者和接收者之間的耦合關係。
#encoding=utf-8##by panda#職責連模式def printInfo(info): print unicode(info, 'utf-8').encode('gbk')#抽象職責類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 CommonManager(Manager): def HandleRequest(self, request): if request.RequestType == '請假' and request.Number <= 2: printInfo('%s:%s 數量%d 被批准' % (self.name, request.RequestContent, request.Number)) else: if self.successor != None: self.successor.HandleRequest(request) #具體職責類:總監class Majordomo(Manager): def HandleRequest(self, request): if request.RequestType == '請假' and request.Number <= 5: printInfo('%s:%s 數量%d 被批准' % (self.name, request.RequestContent, request.Number)) else: if self.successor != None: self.successor.HandleRequest(request)#具體職責類:總經理class GeneralManager(Manager): def HandleRequest(self, request): if request.RequestType == '請假': printInfo('%s:%s 數量%d 被批准' % (self.name, request.RequestContent, request.Number)) elif request.RequestType == '加薪' and request.Number <= 500: printInfo('%s:%s 數量%d 被批准' % (self.name, request.RequestContent, request.Number)) elif request.RequestType == '加薪' and request.Number > 500: printInfo('%s:%s 數量%d 再說吧' % (self.name, request.RequestContent, request.Number))class Request(): RequestType = '' RequestContent = '' Number = 0def clientUI(): jinLi = CommonManager('金力') zongJian = Majordomo('宗健') zhongJingLi = GeneralManager('鐘金利') jinLi.SetSuccessor(zongJian) zongJian.SetSuccessor(zhongJingLi) request = Request() request.RequestType = '請假' request.RequestContent = '小菜請假' request.Number = 1 jinLi.HandleRequest(request) request.RequestType = '請假' request.RequestContent = '小菜請假' request.Number = 5 jinLi.HandleRequest(request) request.RequestType = '加薪' request.RequestContent = '小菜要求加薪' request.Number = 500 jinLi.HandleRequest(request) request.RequestType = '加薪' request.RequestContent = '小菜要求加薪' request.Number = 1000 jinLi.HandleRequest(request) returnif __name__ == '__main__': clientUI();
類圖: