Command pattern
Command pattern example in Java
wikipedia definition:
Command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time
UML diagram from dofactory:
Basic components and workflow:
Command
declares an interface for abstract commands likeexecute()
Receiver
knows how to execute a particular commandInvoker
holdsConcreteCommand
, which has to be executedClient
createsConcreteCommand
and assignReceiver
ConcreteCommand
defines binding betweenCommand
andReceiver
In this way, Command pattern decouples Sender (Client) from Receiver through Invoker. Invoker has complete knowledge of which Command to be executed and Command knows which Receiver to be invoked to execute a particular operation.
Code snippet:
interface Command {
void execute();
}
class Receiver {
public void switchOn(){
System.out.println("Switch on from:"+this.getClass().getSimpleName());
}
}
class OnCommand implements Command{
private Receiver receiver;
public OnCommand(Receiver receiver){
this.receiver = receiver;
}
public void execute(){
receiver.switchOn();
}
}
class Invoker {
private Command command;
public Invoker(Command command){
this.command = command;
}
public void execute(){
this.command.execute();
}
}
class TV extends Receiver{
public String toString(){
return this.getClass().getSimpleName();
}
}
class DVDPlayer extends Receiver{
public String toString(){
return this.getClass().getSimpleName();
}
}
public class CommandDemoEx{
public static void main(String args[]){
// On command for TV with same invoker
Receiver receiver = new TV();
Command onCommand = new OnCommand(receiver);
Invoker invoker = new Invoker(onCommand);
invoker.execute();
// On command for DVDPlayer with same invoker
receiver = new DVDPlayer();
onCommand = new OnCommand(receiver);
invoker = new Invoker(onCommand);
invoker.execute();
}
}
output:
Switch on from:TV
Switch on from:DVDPlayer
Explanation:
In this example,
- Command interface defines
execute()
method. - OnCommand is ConcreteCommand, which implements
execute()
method. - Receiver is the base class.
- TV and DVDPlayer are two types of Receivers, which are passed to ConcreteCommand like OnCommand.
- Invoker contains Command. Itβs the key to de-couple Sender from Receiver.
- Invoker receives OnCommand -> which calls Receiver (TV) to execute this command.
By using Invoker, you can switch on TV and DVDPlayer. If you extend this program, you switch off both TV and DVDPlayer too.
Key use cases:
- To implement callback mechanism
- To implement undo and redo functionality
- To Maintain a history of commands