命令模式(python)

來源:互聯網
上載者:User

命令模式:將一個請求封裝為一個對象,從而使你可用不同的請求對客戶進行參數化;支援對請求排隊、記錄請求日誌,以及可撤銷的操作。

優點:把請求一個操作的對象與知道怎麼執行一個操作的對象分隔開。

#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();

類圖

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.