OOP Design Patterns — Command Pattern
2 min readApr 22, 2021
Definition: The command pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.
Command
public class LightOnCommand implements Command {
Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
@Override
public void undo() {
light.off();
}
}
Invoker
public class HomeAutoController {
Command[] onCommands;
Command[] offCommands;
Command undoCommand;
public HomeAutoController() {
onCommands = new Command[7];
offCommands = new Command[7];
Command noCommand = new NoCommand();
for (int i = 0; i < 7; i++) {
onCommands[i] = noCommand;
offCommands[i] = noCommand;
}
undoCommand = noCommand;
}
public void setCommand (int slot, Command onCommand, Command offCommand) {
onCommands[slot] = onCommand;
offCommands[slot] = offCommand;
}
public void onButtonPushed (int slot) {
onCommands[slot].execute();
undoCommand = onCommands[slot];
}
public void offButtonPushed (int slot) {
offCommands[slot].execute();
undoCommand = offCommands[slot];
}
public void undoPushed () {
undoCommand.undo();
}
}
Receiver is the Light object
- Command pattern decouples an object which makes a request(Invoker), from the object that knows how to perform the requested action (Receiver).
- Command object encapsulates a receiver with an action
- Invokers can be parameterized with objects even in runtime
- Commands may support undo operations as well
- If we need to invoke multiple commands we can use Macro Commands which has a list of Commands
public class MacroCommand implements Command {
Command[] commands;
public MacroCommand(Command[] commands) {
this.commands = commands;
}
@Override
public void execute() {
for (Command command : commands) {
command.execute();
}
}
@Override
public void undo() {
for (Command command : commands) {
command.undo();
}
}
}
- Commands can be used in logging and transactional systems, when a failure happens previous commands can be re-invoked to restore behavior.
Code example can be found in
https://github.com/DineshaKarunathilake/DesignPatterns/tree/master/command