您好,登錄后才能下訂單哦!
如何在Python中使用命令模式?很多新手對此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
命令模式介紹:
在面向?qū)ο缶幊讨?,命令模式是概括所有方法信息的設(shè)計(jì)模式。
此模式對象包涵方法名,及其相關(guān)參數(shù)值。
命令模式是一個(gè)分類的觀察者設(shè)計(jì)模式,在命令模式下,對象被概括為一個(gè)命令表單,此表單包涵了所有用戶需要的方法。
舉個(gè)例子:如果有個(gè)按鈕是用戶接口“red”,當(dāng)被觸碰的時(shí)候,會啟動后臺的“turn red”接口。現(xiàn)在用戶并不知道,通過什么類或者方法的接口能夠讓后臺處理“turn red”操作,但是這個(gè)命令被發(fā)送了(觸碰“red”按鈕),會使得后臺處理“turn red”操作。因此,命令模式給用戶一個(gè)接口,而不用讓用戶了解哪些是實(shí)際執(zhí)行的程序,也不會影響到用戶程序。
實(shí)現(xiàn)命令模式的關(guān)鍵就是讓調(diào)用者不要包涵底層實(shí)際命令執(zhí)行代碼,相同的調(diào)用者應(yīng)該采用相同的接口。
命令模式是由三個(gè)組件構(gòu)成,客戶,調(diào)用者,接受者。
客戶:一個(gè)實(shí)例化的對象
調(diào)用者:決定哪個(gè)方法被調(diào)用
接受者:實(shí)際命令的執(zhí)行者
Example:
實(shí)現(xiàn)一個(gè)開關(guān)
切換ON/OFF
用開關(guān)ON/OFF去硬編碼一個(gè)事件
代碼如下:
class Switch: ''' The INVOKER class''' def __init__(self, flipUpCmd, flipDownCmd): self.__flipUpCommand = flipUpCmd self.__flipDownCommand = flipDownCmd def flipUp(self): self.__flipUpCommand.execute() def flipDown(self): self.__flipDownCommand.execute() class Light: '''The RECEIVER Class''' def turnOn(self): print "The light is on" def turnOff(self): print "The light is off" class Command: """The Command Abstrace class""" def __init__(self): pass def execute(self): pass class FlipUpCommand(Command): '''The Command class for turning on the light''' def __init__(self, light): self.__light = light def execute(self): self.__light.turnOn() class FileDownCommand(Command): '''The Command class for turning off the light''' def __init__(self, light): Command.__init__(self) self.__light = light def execute(self): self.__light.turnOff() class LightSwitch: '''The Client Class''' def __init__(self): self.__lamp = Light() self.__switchUp = FlipUpCommand(self.__lamp) self.__switchDown = FileDownCommand(self.__lamp) self.__switch = Switch(self.__switchUp, self.__switchDown) def switch(self, cmd): cmd = cmd.strip().upper() try: if cmd == "ON": self.__switch.flipUp() elif cmd == "OFF": self.__switch.flipDown() else: print "Argument \"ON\" or \"OFF\" is required" except Exception,msg: print "Exception occured:%s" % msg #Execute if the file is run as a script and not imported as a module if __name__ == "__main__": lightSwitch = LightSwitch() print "Switch ON test" lightSwitch.switch("ON") print "Switch OFF test" lightSwitch.switch("OFF") print "Invalid Command test" lightSwitch.switch("****")
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。