Tuesday, January 15, 2008

* Patterns : Command Behavioral Pattern

Command Patterns helps encapculating/mapping a request to object called command. All commands are derived from base command which has mainly two methods Execute & UnExecute. The commands forwards the request data to Receiver for further processing.

Either client can decide which Command and  Receiver to be invoked or it can be configuration based for loose coupling.

One of the popular places where Command Pattern is used : Model View Controller (MVC) pattern.

Consider the diagram below :

Command

Invoker is the class responsible for executing commands. Since all commands expose common interface, Inovker can be quite generic and appropiate place for logging details.

In the above implementation, client needs to be aware of all three objects Invoker, Command and Receiver. This can be alternately be config based and client just needs to pass request to Invoker.

public class Client
    {
        Receiver receiver;
        BaseCommand command;
        Invoker invoker;

        public void Run()
        {
            receiver = new Receiver();
            command = new ConcreteCommand();
            command.SetReceiver(receiver);
            invoker = new Invoker();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            Console.Read();
        }
    }

Download Source code : Command Behavioral Pattern

Other Design Patterns

1 comment:

  1. hi, can you change your projects to compiling with vs 2005 and .net 2.0 ? by default it imports linq and other namespaces that aren't used in the project (i just remove the references so i can't list them, sorry :(.
    thanks

    ReplyDelete