Please enable Javascript to correctly display the contents on Dot Net Tricks!

Command Design Pattern - C#

  Author : Shailendra Chauhan
Updated On : 26 Sep 2016
Total Views : 51,896   
Support : All C# & .Net
 

Command 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.

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.

YOU MIGHT LIKE
Free Interview Books
 
COMMENTS (0)
14 DEC
ASP.NET MVC with AngularJS Development (online)

MON-FRI 07:30 AM- 09:00 AM IST

Know More
11 DEC
ASP.NET MVC with AngularJS Development (offline)

Sat-Sun 09:30 AM-11:00 AM IST

Know More
5 DEC
AngularJS Development (online)

Mon - Fri     6:30 AM-7:30 AM IST

3 DEC
AngularJS Development (offline)

SAT,SUN     11:00 AM-12:30 PM IST

3 DEC
MEAN Stack Development (offline)

Sat, Sun     (11:00 AM-12:30 PM IST)

26 NOV
ASP.NET MVC with AngularJS Development (offline)

(SAT,SUN)     03:30 PM-05:00 PM IST

24 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     09:30 PM-11:00 PM IST

12 NOV
ASP.NET MVC with AngularJS Development (offline)

SAT,SUN     08:00 AM-09:30 AM

3 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     07:30 AM-09:00 AM IST

25 OCT
.NET Development (offline)

Mon-Fri     9:00 AM-11:00 AM IST

BROWSE BY CATEGORY
 
RECENT ARTICLES
SUBSCRIBE TO LATEST NEWS
 
LIKE US ON FACEBOOK
 

Professional Speaks

+