国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python設計模式之命令模式簡單示例

2020-02-16 11:34:23
字體:
來源:轉載
供稿:網友

本文實例講述了Python設計模式之命令模式。分享給大家供大家參考,具體如下:

命令模式介紹:

在面向對象編程中,命令模式是概括所有方法信息的設計模式。

此模式對象包涵方法名,及其相關參數值。

命令模式是一個分類的觀察者設計模式,在命令模式下,對象被概括為一個命令表單,此表單包涵了所有用戶需要的方法。

舉個例子:如果有個按鈕是用戶接口“red”,當被觸碰的時候,會啟動后臺的“turn red”接口。現在用戶并不知道,通過什么類或者方法的接口能夠讓后臺處理“turn red”操作,但是這個命令被發送了(觸碰“red”按鈕),會使得后臺處理“turn red”操作。因此,命令模式給用戶一個接口,而不用讓用戶了解哪些是實際執行的程序,也不會影響到用戶程序。

實現命令模式的關鍵就是讓調用者不要包涵底層實際命令執行代碼,相同的調用者應該采用相同的接口。

命令模式是由三個組件構成,客戶,調用者,接受者。

客戶:一個實例化的對象

調用者:決定哪個方法被調用

接受者:實際命令的執行者

Example:

實現一個開關
切換ON/OFF
用開關ON/OFF去硬編碼一個事件

代碼如下:

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):  passclass 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 moduleif __name__ == "__main__": lightSwitch = LightSwitch() print "Switch ON test" lightSwitch.switch("ON") print "Switch OFF test" lightSwitch.switch("OFF") print "Invalid Command test" lightSwitch.switch("****")            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 郎溪县| 沽源县| 博客| 原阳县| 苏尼特左旗| 砚山县| 滨州市| 扎鲁特旗| 衢州市| 宁夏| 隆化县| 山西省| 福泉市| 涟源市| 阿鲁科尔沁旗| 东乡| 克东县| 郧西县| 新密市| 寿阳县| 两当县| 蕲春县| 溆浦县| 姚安县| 荣成市| 曲麻莱县| 大关县| 定襄县| 商河县| 华蓥市| 板桥市| 辽阳县| 出国| 新巴尔虎左旗| 泾阳县| 鹿邑县| 桐柏县| 家居| 炎陵县| 吴忠市| 靖远县|