We use commands on a computer to make it perform operations. Usually we expect the the operation must be performed as soon as we type the command. But in certain cases we would like the command to be executed after a delay or some other condition. This is basically instructions for executing the commands.
To achieve this commands are represented as objects. The most important behaviour of this object is to perform the operation done by the command. Apart from this it may also support operations like
- Undoing the operations
- performing the operations in a different context
- simulating the effect of the operations
This type of modelling is a pattern known as Command Pattern
Uses of Command Objects
- GUI buttons and menu items
In Swing and Borland Delphi programming, an Action is a command object. In addition to the ability to perform the desired command, an Action may have an associated icon, keyboard shortcut, tooltip text, and so on. A toolbar button or menu item component may be completely initialized using only the Action object.
- Multi-level undo If all user actions in a program are implemented as command objects, the program can keep a stack of the most recently executed commands. When the user wants to undo a command, the program simply pops the most recent command object and executes its undo() method.
- Progress bars Suppose a program has a sequence of commands that it executes in order. If each command object has a getEstimatedDuration() method, the program can easily estimate the total duration. It can show a progress bar that meaningfully reflects how close the program is to completing all the tasks.
- Networking It is possible to send whole command objects across the network to be executed on the other machines, for example player actions in computer games.
Often a wizard presents several pages of configuration for a single action that happens only when the user clicks the “Finish” button on the last page. In these cases, a natural way to separate user interface code from application code is to implement the wizard using a command object. The command object is created when the wizard is first displayed. Each wizard page stores its GUI changes in the command object, so the object is populated as the user progresses. “Finish” simply triggers a call to execute(). This way, the command class will work.
- Macro recording If all user actions are represented by command objects, a program can record a sequence of actions simply by keeping a list of the command objects as they are executed. It can then “play back” the same actions by executing the same command objects again in sequence. If the program embeds a scripting engine, each command object can implement a toScript() method, and user actions can then be easily recorded as scripts.