- Command Pattern
将命令的请求者(invoker)与命令的执行者(receiver)解耦。 - 类图
- 代码示例
/*
*command Pattern
*
*/
using System;
namespace Pattern03
{
class Program
{
static void Main(string[] args)
{
// Create receiver, command, and invoker
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);//
Invoker invoker = new Invoker();
// Set and execute command
//请求者 设置command
invoker.SetCommand(command);
//执行命令,使用command中的抽象方法
invoker.ExecuteCommand();
Console.ReadKey();
}
}
/// <summary>
/// Command :
/// declares an interface for executing an operation
/// </summary>
abstract class Command
{
protected Receiver receiver;//命令接收者
public Command(Receiver receiver)
{
this.receiver = receiver;
}
public abstract void Execute();
}
/// <summary>
/// ConcreteCommand:
/// ##defines a binding between a Receiver object and an action
/// ##implements Execute by invoking the corresponding operation(s) on Receiver
/// </summary>
class ConcreteCommand : Command
{
//绑定receiver对象
public ConcreteCommand(Receiver receiver) : base(receiver) { }
public override void Execute()
{
receiver.Action();///绑定receiver中的方法
}
}
/// <summary>
/// Receiver:
/// knows how to perform the operations associated with carrying out the request.
/// 执行与请求相关的操作,它具体实现对请求的业务处理。
/// </summary>
class Receiver
{
public void Action()
{
Console.WriteLine("Called Receiver.Action()");
}
}
/// <summary>
/// Invoker :
/// asks the command to carry out the request
/// 请求者,它通过命令对象来执行请求
/// </summary>
class Invoker
{
private Command _command;//带有receiver的command
public void SetCommand(Command command)
{
this._command = command;
}
public void ExecuteCommand()
{
_command.Execute();//通过命令对象来执行请求
}
}
}
- 总结
- 解耦命令请求(invoker)与命令执行(receiver)
ps:
You can implement undo/redo.
You can implement deferred execution of operations.
You can assemble a set of simple commands into a complex
one.
The code may become more complicated since you’re introducing
a whole new layer between senders and receivers.
The client should initialize objects in the following order:
◦ Create receivers.
◦ Create commands, and associate them with receivers if
needed.
◦ Create senders(as Invoker), and associate them with specific commands.