The command pattern should be used when: You need a command to have a life span independent of the original request, or if you want to queue, specify and execute requests at different times. You need undo/redo operations. The command's execution can be stored for reversing its effects.
The Command pattern allows requests to be encapsulated as objects, thereby allowing clients to be parametrized with different requests. The "check" at a diner is an example of a Command pattern. The waiter or waitress takes an order or command from a customer and encapsulates that order by writing it on the check.
Definition: The command pattern encapsulates a request as an object, thereby letting us parameterize other objects with different requests, queue or log requests, and support undoable operations.
Design patterns are commonly defined as time-tested solutions to recurring design problems. The term refers to both the description of a solution that you can read and an instance of that solution as used to solve a particular problem.
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.
Let us focus on the non-implementation aspect of the command design, and some main reasons for using the Command desing pattern grouped in two major categories:
In most programming, you'll want to hide away implementation so that when looking at the top-most problem, it consists of a comprehensible subset of commands/code. I.e. You don't need/want to know the gory details of how a light is switched on, or a car is started. If your focus is to get the car started, you don't need to understand how the engine works, and how it needs fuel to enter the engine, how the valves work, ...
A command gives you this kind of view. You'll immediately understand what the TurnLightOn
command does, or StartCar
. Using a command you'll hide the details of how something is done, whilst clearly indicating the action which is to be executed.
In addition, lets say you later on rebuild your entire Light
class, or a Car
class, which requires you instantiate several different objects, and possibly you need to something else before actually doing your wanted operation. In this case if you had implemented the direct access method, in a lot of places, you would need to change it in all places where you've coded it beforehand. Using a command, you can change the inner details of how to do stuff without changing the calling of the command.
Using a Command interface gives you an extra layer between the code using the command, and the code doing the actual action of the command. This can allow for multiple good scenarios.
Using a command interface, you can also limit access to your objects, allowing you to define another level of security. It could make sense to have a module/library with a fairly open access so that you could handle internal special cases easily.
From the outside, however, you might want to restrict the access to the light so that it is only to be turned on or off. Using commands gives you the ability to limit the interface towards a class.
In addition if you want, you could build a dedicated user access system around the commands. This would leave all of your business logic open and accessible and free of restrictions, but still you could easily restrict access at the command level to enforce proper access.
When building a sufficient large system, commands gives a neat way to bridge between different modules/libraries. Instead of you needing to examine every implementation detail of any given class, you can look into which commands are accessing the class.
And since you are leaving out implementation details to the command itself, you could use a common method to instantiate the command, execute it and review the result. This allows for easier coding, instead of needing to read up on how to instantiate that particular Light
or Car
class, and determining the result of it.
Using commands, you can also do stuff like sequencing of commands. That is since you don't really matter if you are executing the TurnOnLight
or StartCar
command, you can execute sequences of theses as they are executed the same way. Which in turns can allow for chains of commands to be executed, which could be useful in multiple situation.
You could build macros, execute sets of commands which you believe are grouped together. I.e. the command sequence: UnlockDoor
, EnterHouse
, TurnOnLight
. A natural sequence of commands, but not likely to made into a method as it uses different objects and actions.
Commands being rather small in nature, also allows for serialisation quite nicely. This is useful in server-client context, or program-microservice context.
The server (or program) could trigger a command, which then serialises the command, sends it over some communication protocol (i.e. event queue, message queue, http, ... ) to someone actually handling the command. No need to first instantiate the object at the server, i.e. a Light
which could be light-weight (pun intended), or a Car
which could be a really large structure. You just need the command, and possibly a few parameters.
This could be a good place to introduce to the CQRS - Command Query Responsibility Separation pattern for further studies.
Using the extra layer of commands in your system could also allow for logging or tracking commands, if that is a business need. Instead of doing this all over the place, you can gather tracking/logging within the command module.
This allows for easy changes of logging system, or addition of stuff like timeing, or enabling/disabling logging. And it's all easily maintained within the command module.
Tracking of commands also allows for allowing undo actions, as you can choose to re-iterate the commands from a given state. Needs a little bit of extra setup, but rather easily doable.
In short, commands can be really useful as they allow connection between different parts of your soon-to-be-large program, as they are light-weight easily remembered/documented and hides the implementation details when so needed. In addition the commands allows for several useful extensions, which when building a larger system will come in handy: i.e. common interface, sequencing, serialisation, tracking, logging, security.
The possibilities are many, but it'd typically be something like:
opts.register("--on", new LightOnCommand())
.on(Event.ENTER_ROOM, new LightOnCommand())
The general pattern here is that you've got one piece of the code responsible for figuring out that some action needs to be taken without knowing what that action is, and another piece of the code knows how to do an action but not when to do it.
For instance, in that first example, the opts
instance knows that when it sees a command line option --on, it should turn the lights on. But it knows this without actually knowing what "turn the lights on" means. In fact, it could well be that the opts instance came from a third-party library, so it can't know about lights. All it knows about is how to accociate actions (commands) with command-line options that it parses.
You don't have to. Design patterns are simply guidelines that some people in the past have found useful when writing applications of significant complexity.
In your case, if what you have to do is turn the light switch on and off, and not much else, the second option is a no brainer.
Less code is almost always better than more code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With