个人理解:
Invoker维护Command Command维护CommandTarget
UML类图
代码实现
public interface ICommand
{
void Execute();
}
public class Invoker
{
private ICommand command;
public void SetCommand(ICommand command)
{
this.command = command;
}
public void ExecuteCommand()
{
this.command.Execute();
}
}
public class PrintCommand:ICommand
{
public CommandTarget target;
public PrintCommand(CommandTarget target)
{
this.target = target;
}
public void Execute()
{
target.Action();
}
}
public class CommandTarget
{
public void Action()
{
Console.WriteLine("HAHA...The 18th model in 23...Fuck...Bitch...Shit...");
}
}
Python代码实现
class CommandTarget(object):
name=''
class Dog(CommandTarget):
pass
class Cat(CommandTarget):
pass
class Command(object):
def Execute(self):
raise NotImplementedError("abstract class")
class RunCommand(Command):
commandTarget=None
def __init__(self, commandTarget):
self.commandTarget=commandTarget
def Execute(self):
print self.commandTarget.Name + " is running."
class SitCommand(Command):
commandTarget=None
def __init__(self, commandTarget):
self.commandTarget=commandTarget
def Execute(self):
print self.commandTarget.Name + " is sitting."
class CommandHandler(object):
command=None
def __init__(self, command):
self.command=command
def ExecuteCommand(self):
self.command.Execute()
def SetCommand(self, command):
self.command=command
if __name__ == "__main__":
dog=Dog()
dog.Name="dog tom"
cat=Cat()
cat.Name="cat jerry"
sitCommand=SitCommand(cat)
handler=CommandHandler(sitCommand)
handler.ExecuteCommand()
runCommand=RunCommand(dog)
handler.SetCommand(runCommand)
handler.ExecuteCommand()