Holi Sale. Get upto 40% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
Command Design Pattern

Command Design Pattern

23 Aug 2022
Intermediate
107K Views
4 min read
Learn via Video Course & by Doing Hands-on Labs

⭐ .NET Design Patterns Course: Design Patterns in C# Online Training

Command design pattern falls under Behavioral Pattern of Gang of Four (GOF) Design Patterns in .Net. The command pattern is commonly used in the menu systems of many applications such as Editor, IDE etc. In this article, I would like share what is command pattern and how is it work?

What is Command Pattern

In this pattern, a request is wrapped under an object as a command and passed to invoker object. Invoker object pass the command to the appropriate object which can handle it and that object executes the command. This handles the request in traditional ways like as queuing and callbacks.

This pattern is commonly used in the menu systems of many applications such as Editor, IDE etc.

Command Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the command design pattern is given below:

The classes, interfaces, and objects in the above UML class diagram are as follows:

  1. Client

    This is the class that creates and executes the command object.

  2. Invoker

    Asks the command to carry out the action.

  3. Command

    This is an interface which specifies the Execute operation.

  4. ConcreteCommand

    This is a class that implements the Execute operation by invoking operation(s) on the Receiver.

  5. Receiver

    This is a class that performs the Action associated with the request.

C# - Implementation Code

public class Client
{
 public void RunCommand()
 {
 Invoker invoker = new Invoker();
 Receiver receiver = new Receiver();
 ConcreteCommand command = new ConcreteCommand(receiver);
 command.Parameter = "Dot Net Tricks !!";
 invoker.Command = command;
 invoker.ExecuteCommand();
 }
}

public class Receiver
{
 public void Action(string message)
 {
 Console.WriteLine("Action called with message: {0}", message);
 }
}

public class Invoker
{
 public ICommand Command { get; set; }

 public void ExecuteCommand()
 {
 Command.Execute();
 }
}

public interface ICommand
{
 void Execute();
}

public class ConcreteCommand : ICommand
{
 protected Receiver _receiver;
 public string Parameter { get; set; }

 public ConcreteCommand(Receiver receiver)
 {
 _receiver = receiver;
 }

 public void Execute()
 {
 _receiver.Action(Parameter);
 }
}

Command Pattern - Example

Who is what?

The classes, interfaces, and objects in the above class diagram can be identified as follows:

  1. Switch- Invoker class.

  2. ICommand - Command interface.

  3. FlipUpCommand and FlipDownCommand - Concrete Command classes.

  4. Light - Receiver class.

C# - Sample Code

/// <summary>
/// The 'Command' interface
/// </summary>
public interface ICommand
{
 void Execute();
}

/// <summary>
/// The 'Invoker' class
/// </summary>
public class Switch
{
 private List<ICommand> _commands = new List<ICommand>();

 public void StoreAndExecute(ICommand command)
 {
 _commands.Add(command);
 command.Execute();
 }
}

/// <summary>
/// The 'Receiver' class
/// </summary>
public class Light
{
 public void TurnOn()
 {
 Console.WriteLine("The light is on");
 }

 public void TurnOff()
 {
 Console.WriteLine("The light is off");
 }
}

/// <summary>
/// The Command for turning on the light - ConcreteCommand #1 
/// </summary>
public class FlipUpCommand : ICommand
{
 private Light _light;

 public FlipUpCommand(Light light)
 {
 _light = light;
 }

 public void Execute()
 {
 _light.TurnOn();
 }
}

/// <summary>
/// The Command for turning off the light - ConcreteCommand #2 
/// </summary>
public class FlipDownCommand : ICommand
{
 private Light _light;

 public FlipDownCommand(Light light)
 {
 _light = light;
 }

 public void Execute()
 {
 _light.TurnOff();
 }
}

/// <summary>
/// Command Pattern Demo
/// </summary>
class Program
{
 static void Main(string[] args)
 {
 Console.WriteLine("Enter Commands (ON/OFF) : ");
 string cmd = Console.ReadLine();

 Light lamp = new Light();
 ICommand switchUp = new FlipUpCommand(lamp);
 ICommand switchDown = new FlipDownCommand(lamp);

 Switch s = new Switch();

 if (cmd == "ON")
 {
 s.StoreAndExecute(switchUp);
 }
 else if (cmd == "OFF")
 {
 s.StoreAndExecute(switchDown);
 }
 else
 {
 Console.WriteLine("Command \"ON\" or \"OFF\" is required.");
 }

 Console.ReadKey();
 }
}

Command Pattern Demo - Output

When to use it?

  1. Need to implement callback functionalities.

  2. Need to support Redo and Undo functionality for commands.

  3. Sending requests to different receivers which can handle it in different ways.

  4. Need for auditing and logging of all changes via commands.

Read More Articles Related to Design patterns
What do you think?

I hope you will enjoy the Command Pattern while designing your software. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this