Introducing the Command design pattern

Introducing the Command design pattern

Read Time : 3 Minutes

Sunday, 07 May 2023

Design patterns are proven solutions to software design problems. They help improve code quality, promote reusability, and increase maintainability. We use them to save time and produce quality, extensible and flexible code. In this article, we are going to introduce the Command design pattern.

The Command design pattern is a behavioral design pattern that encapsulates a request as an object and separates the sender of the request from the receiver of the request. In simpler terms, it allows you to create a "Command" object that contains all the information necessary to perform a specific action or request, which can then be executed. The Command pattern allows for the creation of reusable commands that can be easily modified or combined to create more complex behaviors.

The Command design pattern consists of the following components:

  • Command: Defines an interface for all commands.
  • Concrete Command: implements the Command interface and contains the necessary information to execute a specific command.
  • Invoker: Requests the execution of a command by calling a method on the Command object.
  • Receiver: The object on which the Command operation is performed.

Below is an example of the Command pattern in C#:

// Receiver: Light
public class Light
{
    public void TurnOn()
    {
        Console.WriteLine("Light is turned on");
    }
    public void TurnOff()
    {
       Console.WriteLine("Light is turned off");
    }
}
// Command interface
public interface ICommand
{
    void Execute();
}
// Concrete command: TurnOnCommand
public class TurnOnCommand : ICommand
{
    private readonly Light _light;
    public TurnOnCommand(Light light)
    {
        _light = light;
    }
    public void Execute()
    {
        _light.TurnOn();
    }
}
// Concrete command: TurnOffCommand
public class TurnOffCommand : ICommand
{
    private readonly Light _light;
    public TurnOffCommand(Light light)
    {
        _light = light;
    }
    public void Execute()
    {
        _light.TurnOff();
    }
}
// Invoker: Switch
public class Switch
{
    private ICommand _turnOnCommand;
    private ICommand _turnOffCommand;
    public Switch(ICommand turnOnCommand, ICommand turnOffCommand)
    {
        _turnOnCommand = turnOnCommand;
        _turnOffCommand = turnOffCommand;
    }
    public void TurnOn()
    {
       _turnOnCommand.Execute();
    }
    public void TurnOff()
    {
       _turnOffCommand.Execute();
    }
}
// Example usage
var light = new Light();
var turnOnCommand = new TurnOnCommand(light);
var turnOffCommand = new TurnOffCommand(light);
var switchObj = new Switch(turnOnCommand, turnOffCommand);
switchObj.TurnOn(); // Output: "Light is turned on"
switchObj.TurnOff(); // Output: "Light is turned off"

In this example, the Light class acts as a Receiver and provides methods to turn it on and off. The TurnOnCommand and TurnOffCommand classes are commands that implement the ICommand interface and receive a Light object in their constructor.

The Switch class acts as an Invoker and receives the commands it is going to execute through the constructor method.

When TurnOn is called on the Switch object, it executes TurnOnCommand, which calls the TurnOn method on the Light object, resulting in the message "Light is turned on" being printed to the console. Similarly, when TurnOff is called, it executes TurnOffCommand, which calls the TurnOff method on the Light object, resulting in the message "Light is turned off" being printed to the console.

Overall, the Command pattern is a powerful and useful pattern that can help you design more modular, maintainable, and extensible code, especially in situations where you need to isolate the invocation and execution of operations.

To read about other design patterns, you can use the list below. There is also a code repository on GitHub that includes all the design patterns.

design patterns

Creational:Factory Design Pattern
Builder Design Pattern
Singleton Design Pattern
Prototype Design Pattern
Abstract Factory Design Pattern
Structural:Adapter Design Pattern
Bridge Design Pattern
Composite Design Pattern
Decorator Design Pattern
Facade Design Pattern
Flyweight Design Pattern
Proxy Design Pattern
Behavioral:Chain of Responsibility Design Pattern
Command Design Pattern
Interpreter Design Pattern
Mediator Design Pattern
Memento Design Pattern
Observer Design Pattern
State Design Pattern
Strategy Design Pattern
Template Method Design Pattern
Visitor Design Pattern
Iterator Design Pattern
  • Share:
reza babakhani
Reza Babakhani

I am Reza Babakhani, a software developer. Here I write my experiences, opinions and suggestions about technology. I hope that what I write is useful for you.

Latest post

Service Mesh Simplifying Microservice Communication

In the ever-evolving landscape of software development, microservices architecture has gained considerable popularity due to its scalability, flexibility, and extensibility. However, as the number of microservices in an application increases, it becomes increasingly challenging to manage their communication and ensure that they are all properly visible. This is where Service Mesh comes into play.

The Importance of Edge Computing

Due to the speed of technological evolution, one of the concepts that has attracted a lot of attention and changes the way we interact with digital systems is edge computing.

What is event-driven architecture?

Event-driven architecture (EDA) is a software design pattern that has become increasingly popular in modern software development. In this architecture, the flow of data is determined by the occurrence of events. Unlike traditional centralized systems that are constantly checking for new status. Event-driven architecture is especially useful for systems that need to process large amounts of data in real-time.

leave a comment