Command Pattern

Introduction and Implementation of Command Pattern


Category: Design Patterns Tags: C#


Introduction

        Command Pattern is Behavioral Design Pattern where an object is encapsulated with all the information required to execute a command or action. Command pattern works with four objects: Command, Receiver, Invoker and client. Where command knows about receiver and invokes receiver’s methods. Receiver actually performs operations which invoked by command. Invoker understands only command interface and able to invoke different commands.

        Behavioral Design Patterns are Design Patterns that identify common communication between objects.

Implementation

        Suppose we have to create a toggle which shows and hides a popup. For that we will create one receiver which actually performs these operations:

interface IReceiver
{
    void ShowPopup();
    void HidePopup();
}

class Receiver : IReceiver
{
    public void ShowPopup()
    {
        Console.WriteLine("Popup Shown");
    }

    public void HidePopup()
    {
        Console.WriteLine("Popup Hidden");
    }
}

Now we have to create commands which will lead to execute ShowPopup and HidePopup methods:

interface ICommand
{
    void Execute();
}

class ShowPopUpCommand : ICommand
{
    private IReceiver _receiver;
    public ShowPopUpCommand(IReceiver receiver)
    {
        _receiver = receiver;
    }

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

class HidePopUpCommand : ICommand
{
    private IReceiver _receiver;
    public HidePopUpCommand(IReceiver receiver)
    {
        _receiver = receiver;
    }

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

Above ICommand is having only one method called Execute and it is implemented in different commands (ShowPopUpCommand, HidePopUpCommand), so now we have two commands which will be used to show and hide popup. Now we have to create Invoker which will encapsulate show and hide commands:

class Toggle
{
    private ICommand _showCommand;
    private ICommand _hideCommand;
public Toggle(ICommand showCommand, ICommand hideCommand) { _showCommand = showCommand; _hideCommand = hideCommand;
}
public void Show() { _showCommand.Execute(); }
public void Hide() { _hideCommand.Execute(); } }

 

Above class is our invoker invoking show and hide commands, from client we will execute code like:

 

ICommand showCommand = new ShowPopUpCommand(newReceiver());
ICommand hideCommand = new HidePopUpCommand(newReceiver());
Toggle toggle = new Toggle(showCommand, hideCommand);
toggle.Show(); toggle.Hide();

And output will be:

Popup Shown

Popup Hidden

 


Like 0 People
Last modified on 15 June 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 126
Questions: 9
Given Best Solutions: 8 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x