Friday, October 17, 2008

Command Pattern - Encapsulate method invocation

The command pattern allows you to decouple the requester of an action (i.e. the object which wants to invoke the method) from the object that actually performs the action. A command object encapsulates a request to do something on a specific object.

Or in other words, objects are used to represent actions. A command object encapsulates an action and its parameters.


There are two objects involved : Invoker and Receiver



class Invoker{

Receiver receiver = null;

void Invoker(Receiver receiver){
this.receiver = receiver;
}

void Method(){
receiver.M1();
}
}

class Receiver{
void M1()
}



In the example above, the invoker and receiver are not decoupled. The invoker knows about the receiver.

Invoker -> Receiver

Now if we want to decouple the invoker and receiver, an option is to let invoker know only about command objects.

Invoker -> Command -> Receiver



public interface Command{
void Execute()
}

public interface ConcreteCommand : Command{

Receiver receiver = null;

public ConcreteCommand(Receiver rcv){
receiver = rcv
}

public void Execute(){
rcv.M1()
}
}

class Invoker{

void Method(){
cmd.Execute();
}

void SetCommand(Command cmd){
}
}


So command pattern gives us a way tp package a piece of computation (receiver and a set of actions) and pass it as a first class objects.

But an important question is still unanswered. Who creates object of concrete command and calls the SetCommand of Invoker object ? Well... it is the client which does that.

Uses of command pattern

1. Implementing thread pools and job schedulers.

2. Macro commands

3. Logging requests

No comments:

Post a Comment