Back to: Design Patterns in C# With Real-Time Examples
Command Design Pattern in C# with Real-time Example
In this article, I am going to discuss the Command Design Pattern in C# with real-time examples. Please read our previous article where we discussed the Template Method Design Pattern in C# with real-time examples. The Command Design Pattern falls under the category of Behavioural Design Pattern. As part of this article, we are going to discuss the following pointers.
- What is the Command Design Pattern?
- Real-time Example of Command Design Pattern
- Command Design Pattern Implementation using C#
- When to use Command Design Pattern in Real-time Application?
What is the Command Design Pattern?
According to Gang of Four (GoF) definitions, the Command Design Pattern is used to encapsulate a request as an object (i.e. a command) and pass to an invoker, wherein the invoker does now knows how to service the request but uses the encapsulated command to perform an action.
Let us understand the above definition with an example. Please have a look at the following diagram. As you can see in the above image, the client will create the command object. The command object has the request (i.e. what to do?). It also has the receiver object reference. The receiver object is nothing but the object which will handle the request. The command object also has the Execute method. The execute 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 does 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 object will call the receiver object method and the receiver object method will perform the necessary action to handle the request. For better understanding please have a look at the following diagram.
This is how the command design pattern works.
Note: As per the command design pattern the command has three things. The first one is the request i.e. the command. The second one is the Receiver object reference and the third one is the Execute method which will call the receiver object method to handle the request.
Real-time Example of Command Design Pattern:
To make you better understand the command design pattern, I have taken the example of a restaurant. In a restaurant, the waiter will be there. What the waiter will do is, waiter will take an order from the customer. The customer will tell what kind of food he/she wants to the waiter. The waiter will note it down on a checklist. Then the waiter passes the checklist to the cook. The cook is the one who will prepare food and given it back to the waiter and the waiter will give it back to the customer.
In this example, the customer is the client. Order i.e. what kind of food the customer wants is the Command. The waiter is the invoker. The Waiter does not know how to cook the food. So, the waiter just passes the request to the receiver i.e. the Cook who will prepare the food and given the food back to the waiter, and the waiter gave it back to the customer.
Command Design Pattern Implementation using C#:
Please have a look at the following image. Here you can see we have three commands. The first one is the Open command. It has the request to open the document. Here, the receiver object is the Document object. The Execute method will call the Open method of the Document object. Similarly, the Save command has the request to save a document. Here, the Execute method will call the save method of the document object. In the same order, the close command has the request to close the document. The Execute method will call the Close method of the document object.
The invoker object (i.e. Menu options) does not know how to handle the requests. So, what the Invoker object will do is, he will call the Execute method of the command object. Here, as you can see the menus having open, save, and close options. So, if the user clicks on the Open menu, then it will execute the Execute method of Open command. The Execute method will call the Open method of the Document object (receiver object) which will open the document.
Similarly, if the user clicks on the close menu, then the invoker object will execute the Execute method of the Close command and the Execute will call the Close method of the Document object will close the document.
Let us implement the above example step by step.
Step1: Creating Receiver object
Create a class file with the name Document.cs and then copy and paste the following code in it. Here, we created the receiver class with three methods i.e. Open, Save, and Close. The Receiver classes contain the business logic to perform the actual actions.
using System; namespace CommandDesignPattern { public class Document { public void Open() { Console.WriteLine("Document Opened"); } public void Save() { Console.WriteLine("Document Saved"); } public void Close() { Console.WriteLine("Document Closed"); } } }
Step2: Creating a Command
First, create an interface with the name ICommand.cs and then copy and paste the following code in it. We declare one method (i.e. Execute) in this ICommand interface which is used for executing a command.
namespace CommandDesignPattern { public interface ICommand { void Execute(); } }
Now, we need to create three command classes by implementing the above ICommand interface.
OpenCommand:
Create a class file with the name OpenCommand.cs and then copy and paste the following code in it.
namespace CommandDesignPattern { public class OpenCommand : ICommand { private Document document; public OpenCommand(Document doc) { document = doc; } public void Execute() { document.Open(); } } }
SaveCommand:
Create a class file with the name SaveCommand.cs and then copy and paste the following code in it.
namespace CommandDesignPattern { class SaveCommand : ICommand { private Document document; public SaveCommand(Document doc) { document = doc; } public void Execute() { document.Save(); } } }
CloseCommand:
Create a class file with the name CloseCommand.cs and then copy and paste the following code in it.
namespace CommandDesignPattern { class CloseCommand : ICommand { private Document document; public CloseCommand(Document doc) { document = doc; } public void Execute() { document.Close(); } } }
Step3: Creating the Invoker
Create a class file with the name MenuOptions.cs and then copy and paste the following code in it.
namespace CommandDesignPattern { public class MenuOptions { private ICommand openCommand; private ICommand saveCommand; private ICommand closeCommand; public MenuOptions(ICommand open, ICommand save, ICommand close) { this.openCommand = open; this.saveCommand = save; this.closeCommand = close; } public void clickOpen() { openCommand.Execute(); } public void clickSave() { saveCommand.Execute(); } public void clickClose() { closeCommand.Execute(); } } }
Note: The Invoker object does not depend on the concrete command or receiver classes. It passes the request to a receiver indirectly, by executing a command.
Step4: Client
Modify the Main method as shown below.
using System; namespace CommandDesignPattern { class Program { static void Main(string[] args) { Document document = new Document(); ICommand openCommand = new OpenCommand(document); ICommand saveCommand = new SaveCommand(document); ICommand closeCommand = new CloseCommand(document); MenuOptions menu = new MenuOptions(openCommand, saveCommand, closeCommand); menu.clickOpen(); menu.clickSave(); menu.clickClose(); Console.ReadKey(); } } }
Output:
When to use Command Design Pattern in Real-time Application?
- When you need to parameterize objects according to action perform.
- When you need to create and execute requests at different times.
- Sending requests to different receivers can handle it 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.
In the next article, I am going to discuss the Visitor Design Pattern in C# with real-time examples. Here, in this article, I try to explain the Command Design Pattern in C# step by step with some examples. I hope you understood the need and use of the Command Design Pattern in C#.
Thank you very much Sir !!!!!
Sir can u tell that how this Command Design Pattern will help us to established undoable operations as well.