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