命令模式:
- 将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
实例代码:
abstract class Commond {
protected Receiver receiver;
public Command(Receiver receiver) {
this.receiver = receiver;
}
abstract public void Execute();
}
- ConcreteCommond类,将一个接收者对象绑定到于一个动作,调用接收者相应的操作,以实现Execute。
class ConcreteCommand : Command {
public ConcreteCommand(Receiver receiver) : base(receiver) {}
public override void Execute() {
receiver.Action();
}
}
class Invoker {
private Command command;
public void SetCommand(Command command) {
this.command = command;
}
public void ExecuteCommand() {
command.Execute();
}
}
- Receiver类,知道如何实施与执行一个与请求相关的操作,任何类都可能作为一个接收者。
class Receiver {
public void Action() {
Console.WriteLine("执行请求!");
}
}
- 客户端代码,创建一个具体命令对象并设定它的接收者。
static void Main(String[] args) {
Receiver r = new Receiver();
Command c = new ConcreteCommand(r);
Invoker i = new Invoker();
i.SetCommand(c);
i.ExecuteCommand();
Console.Read();
}