命令模式:將一個請求封裝為一個對象,從而使你可用不同的請求對客戶進行參數化;支援對請求排隊、記錄請求日誌,以及可撤銷的操作。
優點:把請求一個操作的對象與知道怎麼執行一個操作的對象分隔開。
#encoding=utf-8##by panda#命令模式def printInfo(info): print unicode(info, 'utf-8').encode('gbk')import time#Commandclass Command(): receiver = None def __init__(self, receiver): self.receiver = receiver def Execute(self): pass #具體命令類:拷羊肉串class BakeMuttonCommand(Command): def SetHandsetSoft(self, receiver): Command.__init__(self,receiver) def Execute(self): self.receiver.BakeMutton() def ToString(self): return '拷羊肉串' #具體命令類:拷雞翅class BakeChickenWingCommand(Command): def SetHandsetSoft(self, receiver): Command.__init__(self,receiver) def Execute(self): self.receiver.BakeChickenWing() def ToString(self): return '拷雞翅' #Receiver:拷肉串的人class Barbecuer(): def BakeChickenWing(self): printInfo('拷雞翅!') def BakeMutton(self): printInfo('拷羊肉串!') #Invoker:服務員class Waiter(): commandList = [] def SetOrder(self,command): printInfo('%s 增加訂單:%s' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),command.ToString())) self.commandList.append(command) def CancelOrder(self,command): printInfo('%s 取消訂單:%s' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),command.ToString())) self.commandList.remove(command) def Notify(self): printInfo('\n通知:') for command in self.commandList: command.Execute() def Run(self): printInfo('運行手機通訊錄')def clientUI(): boy = Barbecuer() bakeMuttonCommand1 = BakeMuttonCommand(boy) bakeMuttonCommand2 = BakeMuttonCommand(boy) bakeChickenWingCommand1 = BakeChickenWingCommand(boy) girl = Waiter() girl.SetOrder(bakeMuttonCommand1) girl.SetOrder(bakeMuttonCommand2) girl.SetOrder(bakeChickenWingCommand1) girl.CancelOrder(bakeMuttonCommand1) girl.Notify() returnif __name__ == '__main__': clientUI();
類圖: