introduction to the Command Design pattern

No.of Views1035
Bookmarked0 times
Downloads 
Votes0
By  Chinna Srihari   On  20 Sep 2010 07:09:20
Tag : Design Patterns , General
The Command pattern creates distance between the client that requests an operation and the object that can perform it.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Definition

GoF -> Encapsulate a command request as an object.
The Command pattern creates distance between the client that requests an operation and the object that can perform it.

Design

The Client has a certain way of saying what is required, usually in high-level and domain-specific terms. It Thinks in terms of commands such as On, or Off. The Receivers and there may be several—know how to carry out these requests.

Best example is, we have Switches for TV and Light, Target/receiver. We need to Operator, Invoker, to on or off them. Operator only knows how to execute specific commands. The command object encapsulates the requested operation on the object from the operator. Operator is only execute the command given with the command

UML Diagram

Image Loading

Code

Eg: 1

/// <summary>/// Operations for the Target./// </summary>public interface IOperations
    {
        Boolean IsOn { get; set; }void On();void Off();    
    }/// <summary>/// The interface that provides all commands/// </summary>public interface ICommand
    {void Execute();
    }/// <summary>/// Invoker/// </summary>public class Operator
    {public ICommand Command { get; set; }public void Execute()
        {
            Command.Execute();
        }
    }/// <summary>/// Receiver or target/// </summary>public class Light: IOperations
    {public Boolean IsOn { get; set; }public void On()
        {
            Console.WriteLine("Light is On.....");
            IsOn = true;
        }public void Off()
        {
            Console.WriteLine("Light is Off.....");
            IsOn = false;
        }
     }public class TV : IOperations
    {public Boolean IsOn { get; set; }public void On()
        {
            Console.WriteLine("TV is On.....");
            IsOn = true;
        }public void Off()
        {
            Console.WriteLine("TV is Off.....");
            IsOn = true;
        }
    }/// <summary>///  Command for turning On/Off/// </summary>public class TurnOnOff: ICommand
    {private readonly IOperations _receiver;public TurnOnOff(IOperations receiver)
        {this._receiver = (IOperations)receiver;
        }public void Execute()
        {if (_receiver.IsOn == true)
                _receiver.Off();else_receiver.On();
        }
    }

 Client

Operator operator1 = new Operator() { Command = new TurnOnOff(new Light()) };
            operator1.Execute();
            operator1.Execute();
            

            operator1 = new Operator() { Command = new TurnOnOff(new TV()) };
            operator1.Execute();
            operator1.Execute();

 Eg: 2 with Delegate

/// <summary>/// Operations for the Target./// </summary>public interface IReceiverOperations
    {
        Boolean IsOn { get; set; }void On();void Off();    
    }/// <summary>/// Invoker/// </summary>public delegate void Invoker();/// <summary>/// Receiver or target/// </summary>public class Light: IReceiverOperations
    {public Boolean IsOn { get; set; }public void On()
        {
            Console.WriteLine("Light is On.....");
            IsOn = true;
        }public void Off()
        {
            Console.WriteLine("Light is Off.....");
            IsOn = false;
        }
     }public class TV : IReceiverOperations
    {public Boolean IsOn { get; set; }public void On()
        {
            Console.WriteLine("TV is On.....");
            IsOn = true;
        }public void Off()
        {
            Console.WriteLine("TV is Off.....");
            IsOn = true;
        }
    }/// <summary>///  Command for turning On/Off/// </summary>public class TurnOnOff
    {public static Invoker Off;public static Invoker On;public TurnOnOff(IReceiverOperations receiver)
        {
            Off = receiver.Off;
            On = receiver.On;
        }
    }
}

 Client

new TurnOnOff(new Light());

            TurnOnOff.On();
            TurnOnOff.Off();new TurnOnOff(new TV());

            TurnOnOff.On();
            TurnOnOff.Off();

That's all. i hope this is help to you all.thank you for reading.

 
Sign Up to vote for this article
 
About Author
 
Chinna Srihari
Occupation-Software Engineer
Company-
Member Type-Junior
Location-India
Joined date-17 Jun 2010
Home Page-
Blog Page-
Having 12 + years of IT experience, 2.5 years as Technical Management experience and 1.5 year of onsite coordinator experience and rest 8+ years of technical activities including Project Leader, Tech Lead, Designer, PQL, and Developer experience in Quality Management System (CMM-level 5, SEI-CMM-level 5).
 
 
Other popularSectionarticles
    Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
    Published Date : 23/Oct/2010
    This is a quite simple design pattern, let me tell you one thing there are many design patterns that they are implicitly singletons. I rather recommend to understanding this one first before going through other patterns.
    Published Date : 21/Oct/2010
    As a developer we might have noticed that creation of some class is very difficult and number of time that we need to create. Such object creation every time is very expensive in terms of system resources. If we can cache that kind of object show how will surely boost the application performance and resource usage can be saved. This where object pool design pattern will help development community to cache the objects. Some time it is also called as Object cache or Resource cache design pattern.
    Published Date : 21/Oct/2010
    Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.
    Published Date : 22/Oct/2010
    A fully initialized instance to be copied or cloned. The Prototype pattern specifies the kind of objects to create using a prototypical instance.
    Published Date : 22/Oct/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top