paint-brush
How to Transform Your C# Code With the Command Design Patternby@ssukhpinder
260 reads

How to Transform Your C# Code With the Command Design Pattern

by Sukhpinder SinghFebruary 22nd, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Command Design Pattern is one of the behavioural design patterns used to encapsulate a request as an object. It enables to parameterize clients with different requests, queue or log requests, and support undoable operations. This article will discuss the Command Design Pattern in C# with an example. It demonstrates command design patterns using the C# programming language.
featured image - How to Transform Your C# Code With the Command Design Pattern
Sukhpinder Singh HackerNoon profile picture

Command Design Pattern is one of the behavioral design patterns used to encapsulate a request as an object, thus enabling to parameterize clients with different requests, queue or log requests, and support undoable operations.


This article will discuss the Command Design Pattern in C# with an example.

Prerequisites

  • Basic knowledge of OOPS concepts.


  • Any programming language knowledge.


The article demonstrates command design patterns using the C# programming language. So, to begin with, C#


Introduction to C#


C# has been around for quite some period, and it continues to develop, obtaining more enhanced features.medium.com

Learning Objectives

  • How to code using an adapter command pattern

Getting Started

Introduction to Command Design Pattern

The Command Design Pattern decouples the object that invokes the operation from the one that knows how to perform it. The pattern provides a way to associate requests with things, where each request is represented as an object with its properties and methods.


The critical elements in the Command Pattern are:


  • The Command Interface: Defines the standard interface for all commands.


  • The Concrete Command: Implements the Command Interface and implements the execute method.


  • The Invoker Holds a reference to the command and invokes the command when required.


  • The Receiver: Knows how to perform the operations associated with the command.

Example of Command Design Pattern in C#

Let us consider an example of a simple calculator that can perform arithmetic operations like addition, subtraction, multiplication, and division.


We can use the Command Design Pattern to implement these operations as commands.


First, we will create a Command interface that will define the common interface for all commands. This interface will have an execute method that the concrete commands will implement.


public interface ICommand
{
    void Execute();
}


Next, we will create concrete command classes for each operation, which will implement the ICommand interface and provide the implementation for the execute method.


public class AdditionCommand : ICommand
{
    private readonly Calculator _calculator;
    private readonly int _operand;
    public AdditionCommand(Calculator calculator, int operand)
        {
            _calculator = calculator;
            _operand = operand;
        }
        public void Execute()
        {
            _calculator.Add(_operand);
        }
    }
    public class SubtractionCommand : ICommand
    {
        private readonly Calculator _calculator;
        private readonly int _operand;
        public SubtractionCommand(Calculator calculator, int operand)
        {
            _calculator = calculator;
            _operand = operand;
        }
        public void Execute()
        {
            _calculator.Subtract(_operand);
        }
    }
    public class MultiplicationCommand : ICommand
    {
        private readonly Calculator _calculator;
        private readonly int _operand;
        public MultiplicationCommand(Calculator calculator, int operand)
        {
            _calculator = calculator;
            _operand = operand;
        }
        public void Execute()
        {
            _calculator.Multiply(_operand);
        }
    }
    public class DivisionCommand : ICommand
    {
        private readonly Calculator _calculator;
        private readonly int _operand;
        public DivisionCommand(Calculator calculator, int operand)
        {
            _calculator = calculator;
            _operand = operand;
        }
        public void Execute()
        {
            _calculator.Divide(_operand);
        }
    }
}


The Calculator class will act as the receiver and know how to perform the arithmetic operations.


public class Calculator
{
    private int _result;
    public void Add(int operand)
    {
        _result += operand;
    }
    public void Subtract(int operand)
    {
        _result -= operand;
    }
    public void Multiply(int operand)
    {
        _result *= operand;
    }
    public void Divide(int operand)
    {
        if (operand != 0)
        {
            _result /= operand;
        }
    }
    public int GetResult()
    {
        return _result;
    }
}


Finally, we will create an Invoker class, which will hold a reference to the command and invoke the command when required.


public class CalculatorInvoker
{
    private ICommand _command;
    public void SetCommand(ICommand command)
    {
        _command = command;
    }
    public void ExecuteCommand()
    {
        _command.Execute();
    }
}


Now, let us see how these classes can perform arithmetic operations.


static void Main(string[] args) { 
  Calculator calculator = new Calculator(); 
  CalculatorInvoker invoker = new CalculatorInvoker();

  // Create commands for arithmetic operations
  AdditionCommand additionCommand = new AdditionCommand(calculator, 5);
  SubtractionCommand subtractionCommand = new SubtractionCommand(calculator, 3);
  MultiplicationCommand multiplicationCommand = new MultiplicationCommand(calculator, 2);
  DivisionCommand divisionCommand = new DivisionCommand(calculator, 4);

  // Execute commands using invoker
  invoker.SetCommand(additionCommand);
  invoker.ExecuteCommand();
  invoker.SetCommand(subtractionCommand);
  invoker.ExecuteCommand();
  invoker.SetCommand(multiplicationCommand);
  invoker.ExecuteCommand();
  invoker.SetCommand(divisionCommand);
  invoker.ExecuteCommand();
  // Get result from calculator
  int result = calculator.GetResult();
  Console.WriteLine("Result: " + result); // Output: Result: 1
}


In the above example, we created four concrete command objects for the arithmetic operations and used the Invoker to execute these commands. The Invoker does not know about the definite commands; it only knows about the Command interface.


The concrete controls encapsulate the receiver object (Calculator) and the arguments required for the operations.

Conclusion

Overall, the Command Design Pattern provides a flexible and extensible way to encapsulate requests as objects and decouple the object that invokes the operation from the one that knows how to perform it.


In summary, the Command Design Pattern is a helpful way to decouple the object that invokes the operation from the one that knows how to perform it.


It provides a way to associate requests with things, where each request is represented as an object with its properties and methods. In C#, we can use interfaces and classes to implement this pattern.

Follow me on

C# Publication, LinkedIn, Instagram, Twitter, Dev.to, BuyMeACoffee


Also published here