Commands and Command Processors

Instead of directly modifying the model in response to user inputs, controllers create commands and forward them to a centralized command processor. It is the job of the command processor to execute the commands.

One advantage of this arrangement is that it makes it easy to provide several types of controllers that do the same thing. For example, most menu selections have corresponding tool bar buttons and hot key combinations that perform the same action. More advanced users prefer the tool bar or keyboard because they are faster to use, while beginners can make the GUI simpler by hiding the tool bar. We can avoid coding redundancy by having multiple controllers create the same type of command. Thus a menu selection and its corresponding toll bar button can create the same type of command object:

Controllers send the commands they create to a centralized command processor object. It is the job of the command processor to execute the commands it receives, but it can do a lot more. For example, by keeping track of all commands, the command processor can implement application-independent commands such as undo, redo, and rollback. All of this is summarized in the command processor pattern:

Command Processor [POSA] [Go4]

Other Names

Commands are also called actions and transactions.

Problem

A framework wishes to provide an undo/redo mechanism, and perhaps other features such as scheduling, concurrency, roll back, history mechanisms, or the ability to associate the same action to different types of controllers (e.g. for novice and advanced user).

Solution

Create an abstract base class for all commands in the framework. This base class specifies the interface all concrete command types must implement.

Commands are created by controllers such as menu selections, buttons, text boxes, and consoles. The commands are forwarded to a command processor, which can store, execute, undo, redo, and schedule them.

In the smart command variant of the pattern, commands know how to execute themselves. In the dumb command variant commands are simply tokens, and the command processor must know how to execute them.

Scenario

When a user clicks a button, selects a menu item, or activates some other type of controller, the controller creates an appropriate command object, then asks the command processor to execute it. If we are using dumb commands, then either the command processor must know how to execute the command, which implies some knowledge of the application, or the command processor must ask some other component, such as the model, to execute the command. In the smart command variant, the commands are objects that know how to execute and undo themselves: