Python 设计模式-- 命令模式
JAVA 中的命令模式大家估计都很熟悉,就是可以讲命令调用者和命令的执行者进行解耦。
看一下类图:
。
第一步: 目前Python设计的实体有电灯,和仓库门 (Light,GarageDoor)
Entity
1 #coding = utf8 2 class Light(object): 3 def on(self): 4 print '---the light on---' 5 def off(self): 6 print '---the light off---' 7 8 class GarageDoor(object): 9 def action_up(self,*args): 10 print '--- the garageDoor open ---' 11 def action_down(self,*args): 12 print '--- the garageDoor down ---' 13 14 def action_stop(self,*args): 15 print '--- the garageDoor stop ---' 16 17 def action_lighton(self,*args): 18 print '--- the garageDoor lighton ---' 19 20 def action_lightoff(self,*args): 21 print '--- the garageDoor lightoff---'
具体的命令如Light.on,Light.off 等在实体类中进行了定义。
第二步: 进行,AbstractCommand ,和ConcreteCommand 的实现。
Command
1 class Command(object): 2 def callback(self,invoker,name,*args): 3 method=getattr(invoker,name,None) 4 #print method 5 #print args 6 if callable(method): 7 method(*args) 8 #print invoker 9 10 def setTask(self,tasks): 11 pass 12 13 def execute(self): 14 pass 15 16 class NoCommand(object): 17 def setTask(self): 18 pass 19 def execute(self): 20 pass 21 22 # the type no constraint 23 class LightOnCommand(Command): 24 def __init__(self,light): 25 self.light=light 26 27 def execute(self): 28 self.light.on() 29 30 31 32 33 class GarageDoorCommand(Command): 34 35 36 def __init__(self,garageDoor,tasks): 37 self.garageDoor = garageDoor 38 self.tasks=tasks 39 40 def setTasks(self,tasklist): 41 self.tasks=tasklist 42 43 44 def execute(self): 45 for task in self.tasks: 46 self.callback(garageDoor,task[0],task[1])
由于Python 中的接口,和继承都在 通过标签实现的。这一点同JAVA 有很大的不同
Invoker
1 class SimpleRemoteControl(object): 2 def __init__(self,command): 3 self.command=command 4 def buttonWasPressed(self): 5 self.command.execute() 6 7 8 class RemoteControl(object): 9 commands_open=[None for i in range(8)] 10 commands_off=[None for i in range(8)] 11 12 def __init__(self): 13 pass
最后在Invoker进行调用,其中的Light,GarageDoor 相当于Receiver 。
这整个过程类似于JAVA 中Command 模式的实现了。