Design Patterns – Command

By | 31/03/2021

From https://en.wikipedia.org/wiki/Command_pattern:
“In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.”
In a nutshell, we can use the Command Pattern 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.
In the Command Pattern there are five objects:
Command: an interface/abstract class for executing an action
ConcreteCommand: extends the Command and implements the method
Receiver: contains the logic for executing the operations associated with the request
Invoker: uses Command object to carry out the request
Client: instantiates a ConcreteCommand class

In this post, we will use the Command to create a simple calculator.

BEFORE STARTING, I WANT TO REMEMBER THAT I PREFERRED USING A SIMPLE CODE IN ORDER TO UNDERSTAND “THE COMMAND PATTERN” EASIER.

We create a Console application called Calculator and add these Classes:

RECEIVER

[CORECALC.CS]

namespace CommandPattern
{
    public class CoreCalc
    {
        private int _val1, _val2;

        public CoreCalc(int val1, int val2)
        {
            _val1 = val1;
            _val2 = val2;
        }

        public int Add()
        {
            return _val1 + _val2;
        }

        public int Division()
        {
            return _val1 / _val2;
        }

        public int Multiplication()
        {
            return _val1 * _val2;
        }

        public int Subtraction()
        {
            return _val1 - _val2;
        }
    }
}



COMMAND

[COMMAND.CS]

namespace CommandPattern
{
    public abstract class Command
    {
        private CoreCalc _coreCalc;
        public Command(CoreCalc coreCalc)
        {
            _coreCalc = coreCalc;
        }
        public abstract int Execute();
    }
}



CONCRETE COMMAND

[COMMANDADD.CS/COMMANDSUBTRACTION.CS/COMMANDMULTIPLICATION.CS/COMMANDDIVISION.CS]

namespace CommandPattern
{
    public class CommandAdd : Command
    {
        CoreCalc _coreCacl;

        public CommandAdd(CoreCalc coreCal): base(coreCal)
        {
            _coreCacl = coreCal;
        }

        public override int Execute()
        {
            return _coreCacl.Add();
        }
    }
}

namespace CommandPattern
{
    public class CommandSubtraction : Command
    {
        CoreCalc _coreCalc;

        public CommandSubtraction(CoreCalc coreCalc): base(coreCalc)
        {
            _coreCalc = coreCalc;
        }
        public override int Execute()
        {
            return _coreCalc.Subtraction();
        }
    }
}

namespace CommandPattern
{
    public class CommandMultiplication : Command
    {
        CoreCalc _coreCalc;

        public CommandMultiplication(CoreCalc coreCalc): base(coreCalc)
        {
            _coreCalc = coreCalc;
        }

        public override int Execute()
        {
            return _coreCalc.Multiplication();
        }
    }
}

namespace CommandPattern
{
    public class CommandDivision : Command
    {
        CoreCalc _coreCalc;

        public CommandDivision(CoreCalc coreCalc): base(coreCalc)
        {
            _coreCalc = coreCalc;
        }

        public override int Execute()
        {
            return _coreCalc.Division();
        }
    }
}



INVOKER

[INVOKER.CS]

namespace CommandPattern
{
    public class Invoker
    {
        Command _command;

        public void SetCommand(Command command)
        {
            _command = command;
        }

        public int Execute()
        {
            return _command.Execute();
        }
    }
}



Finally, we define the method Main (CLIENT):

using System;

namespace CommandPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Insert Value1");
            int val1 = System.Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Insert Value2");
            int val2 = System.Convert.ToInt32(Console.ReadLine());

            // Receiver
            CoreCalc objCalc = new CoreCalc(val1, val2);

            // Concrete Commands
            CommandAdd commAdd = new CommandAdd(objCalc);
            CommandSubtraction commSub = new CommandSubtraction(objCalc);
            CommandDivision commDiv = new CommandDivision(objCalc);
            CommandMultiplication commMul = new CommandMultiplication(objCalc);

            // Invoker
            Invoker objInvoker = new Invoker();


            // Add
            objInvoker.SetCommand(commAdd);
            Console.WriteLine($"{val1} + {val2} = {objInvoker.Execute()}");

            // Subtraction
            objInvoker.SetCommand(commSub);
            Console.WriteLine($"{val1} - {val2} = {objInvoker.Execute()}");

            // Multiplication
            objInvoker.SetCommand(commMul);
            Console.WriteLine($"{val1} * {val2} = {objInvoker.Execute()}");

            // Division
            objInvoker.SetCommand(commDiv);
            Console.WriteLine($"{val1} / {val2} = {objInvoker.Execute()}");
        }
    }
}



We have done and now, if we run the application, this will be the result:



Leave a Reply

Your email address will not be published. Required fields are marked *