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 like execute()
Receiver
knows how to execute a particular commandInvoker
holds ConcreteCommand
, which has to be executedClient
creates ConcreteCommand
and assign Receiver
ConcreteCommand
defines binding between Command
and Receiver
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,
execute()
method.execute()
method.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: