We continue our look into the behavioral patterns with an examination of the Command pattern. This is another one of them that will seem very familiar. In fact, you have probably made use of this in one way or another in your code.
The Command Pattern Defined
As always, we will start with the “Gang of Four” intent to set the stage for our discussion.
“Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.”
This intent is short and sweet both in the description and in implementation. The goal is to create an object that can be passed around as a function. When we do this, we are allowed to do things like performing a callback, transfer an action to another time or system. This can include performing an undo or other transaction types. A GUI menu is a perfect visual representation of this idea. Think of clicking a menu item as a command. The command is executed based on the object (menu item) that it is called on.
Applying The Pattern
The implementation of this pattern is an interface that provides an execute or run method. In other cases, a command pattern can be implemented through a class. In this case, it takes a receiver that can perform the action. The second option is a way to allow things like queueing up commands. It is also useful for storing them for execution at a different time. This may seem like an obvious extension of an object-oriented design by being able to abstract functions from classes, but it still has enough wrinkles to make this a good pattern to know.
Java, PHP, C#, etc.
As mentioned before, there are a couple of ways to implement a command pattern. The good news is that this tends to be simple enough that any language implementation will look almost identical to any other. The languages that make heavy use of callbacks may be better places to find examples of how to implement this pattern.
One Reply to “Software Design – The Command Pattern”