Command Pattern

  • Behavioral pattern
  • The intent of this pattern is to encapsulate request as an object, there by letting you parametrize clients with different requests, queue or log requests and support undoable operations.
  • Command pattern allows decoupling the requestor of an action from the receiver
    • very common in mobile or rich UI development
  • Invoker:- asks command to cary out a request
  • Command :- declares an interface for executing an action
  • ConcreteCommand:- defines and binding between a receiver and action. It implements execute by invoking the corresponding operations on receiver.
  • Receiver:- knows how to perform the operations associated with caryying out a request.
  • Client :- creates the concreteCommand and sets it receiver.
				
					namespace commandpattern
{
    public interface ICommand
    {
        void Execute();
    }

    class Light //Receiver
    {
        public void LightOn()
        {
            Console.WriteLine("Lights are on now");
        }
        public void LightOff()
        {
            Console.WriteLine("Lights are off now");

        }
    }

    class LightOnCommand : ICommand
    {
        private readonly Light _light;

        public LightOnCommand(Light light)
        {
            _light = light;
        }
        public void Execute()
        {
            _light.LightOn();
        }
    }

    class LightOffCommand : ICommand
    {
        private readonly Light _light;

        public LightOffCommand(Light light)
        {
            _light = light;
        }
        public void Execute()
        {
            _light.LightOff();
        }
    }

    public class Invoker
    {
        private readonly ICommand lightOn;
        private readonly ICommand lightOff;

        public Invoker(ICommand on, ICommand off)
        {
            this.lightOn = on;
            this.lightOff = off;
        }

        public void ClickOn()
        {
            lightOn.Execute();
        }

        public void ClickOff()
        {
            lightOff.Execute();
        }
    }
}

				
			
				
					using commandpattern;

var light = new Light();
var lightCommandObj =new Invoker(new LightOnCommand(light), new LightOffCommand(light));
lightCommandObj.ClickOn();
Console.WriteLine("......");
lightCommandObj.ClickOff();

				
			

Lights are on now
……
Lights are off now

Leave a Comment