命令模式介绍:
在面向对象编程中,命令模式是概括所有方法信息的设计模式。
此模式对象包涵方法名,及其相关参数值。
命令模式是一个分类的观察者设计模式,在命令模式下,对象被概括为一个命令表单,此表单包涵了所有用户需要的方法。
举个例子:如果有个按钮是用户接口“red”,当被触碰的时候,会启动后台的“turn red”接口。现在用户并不知道,通过什么类或者方法的接口能够让后台处理“turn red”操作,但是这个命令被发送了(触碰“red”按 钮),会使得后台处理“turn red”操作。因此,命令模式给用户一个接口,而不用让用户了解哪些是实际执行的程序,也不会影响到用户程序。
实现命令模式的关键就是让调用者不要包涵底层实际命令执行代码,相同的调用者应该采用相同的接口。
命令模式是由三个组件构成,客户,调用者,接受者。
客户:一个实例化的对象
调用者:决定哪个方法被调用
接受者:实际命令的执行者
Example:
- 实现一个开关
- 切换ON/OFF
- 用开关ON/OFF去硬编码一个事件
代码如下:
1 class Switch: 2 ''' The INVOKER class''' 3 4 def __init__(self, flipUpCmd, flipDownCmd): 5 self.__flipUpCommand = flipUpCmd 6 self.__flipDownCommand = flipDownCmd 7 8 def flipUp(self): 9 self.__flipUpCommand.execute() 10 11 def flipDown(self): 12 self.__flipDownCommand.execute() 13 14 class Light: 15 '''The RECEIVER Class''' 16 def turnOn(self): 17 print "The light is on" 18 19 def turnOff(self): 20 print "The light is off" 21 22 class Command: 23 """The Command Abstrace class""" 24 def __init__(self): 25 pass 26 def execute(self): 27 pass 28 29 class FlipUpCommand(Command): 30 '''The Command class for turning on the light''' 31 32 def __init__(self, light): 33 self.__light = light 34 35 def execute(self): 36 self.__light.turnOn() 37 38 class FileDownCommand(Command): 39 '''The Command class for turning off the light''' 40 41 def __init__(self, light): 42 Command.__init__(self) 43 self.__light = light 44 45 def execute(self): 46 self.__light.turnOff() 47 48 class LightSwitch: 49 '''The Client Class''' 50 def __init__(self): 51 self.__lamp = Light() 52 self.__switchUp = FlipUpCommand(self.__lamp) 53 self.__switchDown = FileDownCommand(self.__lamp) 54 self.__switch = Switch(self.__switchUp, self.__switchDown) 55 56 def switch(self, cmd): 57 cmd = cmd.strip().upper() 58 try: 59 if cmd == "ON": 60 self.__switch.flipUp() 61 elif cmd == "OFF": 62 self.__switch.flipDown() 63 else: 64 print "Argument \"ON\" or \"OFF\" is required" 65 except Exception,msg: 66 print "Exception occured:%s" % msg 67 68 69 #Execute if the file is run as a script and not imported as a module 70 71 if __name__ == "__main__": 72 lightSwitch = LightSwitch() 73 74 print "Switch ON test" 75 lightSwitch.switch("ON") 76 77 print "Switch OFF test" 78 lightSwitch.switch("OFF") 79 80 print "Invalid Command test" 81 lightSwitch.switch("****")
总结:面向对象的方法,就是这么牛叉啊,代码看得让人头晕,层层的封装。警惕面向对象编程的过度对象化。