The Command design pattern encapsulates a request as an object, thereby letting you paramize clients with different requests, queue or log requests, and support undoable operations.
命令模式封装请求作为一个对象,因此让你参数化客户端用不同的requests,队列或者日志requests,并且支持撤销操作。
UML Class Diagram
The client will create the command object, the command object involves three things. First, the command object has the request. sencond, it also has the Receiver Object Referece, the Receiver object is nothing but the object which will handle the request. Third,the command object alos has the excute method, the excute method will call the receiver object method and the receiver object method will handle the request.
As per the Command Design Pattern, the Command Object will be passed to the Invoker object. The Invoker Object class not know how to handle the request. What the Invoker will do is ,it will call the Execute method of the Command Object.The Execute method of the command will call the Receiver Object Method. The Receiver Object Method will perform the necessary action to handle the request.
Receiver: This is a class that contains the actual implementation of the method that the client wants to call.
Command: This is going to be an interface that specifies the excute operation.
ConcreteCommand: There are going to be classes that implement the ICommand interface and provide implementations for the excute operation.As part of the Excute method, It is going to invoke operations on the Receiver object.
Invoker: The Invoker is going to be a class and asks the command to carry out the action.
Clilent: This is the class that creates and executes the command object.
Structure Code in C#
public abstract class Command { protected Receiver receiver; public Command(Receiver receiver) { this.receiver = receiver; } public abstract void Execute(); } public class ConcreteCommand : Command { public ConcreteCommand(Receiver receiver):base(receiver) { } public override void Execute() { receiver.Action(); } }Command
public class Receiver { public void Action() { Console.WriteLine($"Called Receiver.Action()"); } }Receiver
public class Invoker { public Command command; public void SetCommand(Command command) { this.command = command; } public void ExecuteCommand() { command.Execute(); } }Invoker
When to use Command Design Pattern in Real-time Application?
- When you need to parameterize objects according to the action performed.
- When you need to create and execute requests at different times.
- Sending requests to different receivers can handle in different ways.
- When you need to support rollback, logging, or transaction functionality.
- When you need to implement callback functionality
- The source of the request should be decoupled from the object that actually handles the request.