Monday, 31 May 2021

Command Design Pattern in C#

    

 Introduction

    Command design pattern encapsulates request as an object which has all the information needed to perform an action or invoke a method or trigger an event at later time. It supports undoable action.

It is a behavior design pattern.

It  deals with below problems

1. Decouples the request receiver and request invoker.

2. Code is extensible as new Receiver and command be added in future.

UML Diagram


Example Basic structure program

using System;

public class Program
{
public static void Main()
{
var receiver = new Receiver();
var command = new ConcreteCommand(receiver);
var invoker = new Invoker(command);
invoker.DoAction();
}
}

public class Receiver
{
public void DoOperation()
{
    Console.WriteLine("Receiver is doing the operation");
}
}

public interface ICommand
{
    void Execute();
}

public class ConcreteCommand:ICommand
{
        private Receiver _receiver;
        public ConcreteCommand(Receiver receiver)
        {
            _receiver = receiver;
        }

public void Execute()
{
    _receiver.DoOperation();
}
}

public class Invoker
{
    private ICommand _command;
    public Invoker(ICommand command)
    {
        _command = command;
    }

    public void DoAction()
    {
        _command.Execute();
    }
}

In the above code, we can see Command and Invoker have been created separately. This means 
Invoker can execute the command at a later point of time or deferred execution of command.
Command can be queued and executed.
Command can be created on one server & can be executed on another server in distributed systems.
Waiter and Chef (cook) are very good example of command pattern. As Waiter takes the order from the customer, he passed it to chef. Chef prepares the food and waiter serves it to customer.  

Real World Example
    Write to me for real world example.










No comments:

Post a Comment