The main motivation for using the Command pattern is that the executor of the command does not need to know anything at all about what the command is, what context information it needs on or what it does. All of that is encapsulated in the command.
This allows you to do things such as have a list of commands that are executed in order, that are dependent on other items, that are assigned to some triggering event etc.
In your example, you could have other classes (e.g. Air Conditioner
) that have their own commands (e.g. Turn Thermostat Up
, Turn Thermostat Down
). Any of these commands could be assigned to a button or triggered when some condition is met without requiring any knowledge of the command.
So, in summary, the pattern encapsulates everything required to take an action and allows the execution of the action to occur completely independently of any of that context. If that is not a requirement for you then the pattern is probably not helpful for your problem space.
Here's a simple use case:
interface Command {
void execute();
}
class Light {
public Command turnOn();
public Command turnOff();
}
class AirConditioner {
public Command setThermostat(Temperature temperature);
}
class Button {
public Button(String text, Command onPush);
}
class Scheduler {
public void addScheduledCommand(Time timeToExecute, Command command);
}
Then you can do things such as:
new Button("Turn on light", light.turnOn());
scheduler.addScheduledCommand(new Time("15:12:07"), airCon.setThermostat(27));
scheduler.addScheduledCommand(new Time("15:13:02"), light.turnOff());
As you can see the Button
and Scheduler
don't need to know anything at all about the commands. Scheduler
is an example of a class that might hold a collection of commands.
Note also that in Java 8 functional interfaces and method references have made this type of code even neater:
@FunctionalInterface
interface Command {
void execute();
}
public Light {
public void turnOn();
}
new Button("Turn On Light", light::turnOn);
Now the methods that are turned into commands don't even need to know about commands - as long as they have the correct signature you can quietly create a anonymous command object by referencing the method.