Command pattern

In object-oriented programming command (also command; english command) a design pattern that belongs to the category of behavior ( behavioral patterns ). In this design pattern, the command object encapsulates a command to allow as to make operations in a queue to keep log entries and make operations undone. It is one of the GoF patterns.

Use

For example, if a button is to be linked in a GUI with an action command is used to parameterize the action to perform. It therefore represents the object-oriented equivalent to the callback functions (callback function) dar. Here, the creation of the commands and the actual execution at different times or in a different context (thread, process, computers) can take place.

Implementation of an undo mechanism ( undo): Each time you run the necessary to reverse data is stored in the object and the object itself secured on a stack. To implement the contrary restore ( redo ), a second stack for the commands undone enough.

Actors

The command is the base class of all commands. A more concrete instruction stores the necessary condition for performing, including typically a reference to the receiver and implements the command interface.

The client generates a specific command and provides it with a reference to the receiver and all other necessary information. It returns to the caller, a reference to the specific command.

The caller has one or more references to commands and ask it if necessary to carry out their action. At the receiver, no special requirements are imposed. He must know nothing about the other actors. Thus, each class can serve as a receiver. The concrete command invokes methods of the receiver object to perform its action.

Pros & Cons

Triggering and executive are decoupled. Command objects can also be manipulated like other objects (changing, filtering, caching, ...). Command objects can be combined into complex commands ( macros realized as a composite ).

Since for every command, a new class is needed, the number of large and fast implementation can thus be confusing.

Example

Linking GUI elements provides a simple example with buttons or menu items is:

  • Specific commands then implement actions such as file open, undo or move cursor to right
  • Clients are the application or dialogues.
  • Caller are buttons, menu items and hotkeys.
  • Receivers are the application ( file open ) or document ( Undo cursor to the right )
111963
de