Command

From CSSEMediaWiki
Revision as of 03:20, 4 October 2008 by Dominic Winkler (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

In the Command pattern objects are used to represent actions. An action and its parameters are encapsulated by a command object.


Contents

Usage

Sometimes you need to issue a request to an object without even knowing anything about the requested operation or the receiving object itself, then it is useful to apply the Command pattern. A situation where to use the Command pattern would be for example the implementation of a menu in a GUI. Every single menu item has its own corresponding concrete command object, which implement a command interface. When the user clicks on a menu item the menu item calls the execute() method of its command object. The execute() method carries out an operation. The concrete commands store the receiver and call up one or more operations on the receiver. Good examples for menu items would be the opening and closing of documents or also pasting some text.

Often it might look

  • a command object is a convenient place to collect code and data related to a specific action
  • treating commands as objects supports undo-able operations, provided that the command objects are stored (eg in a stack)
  • the construction of a command and the actual execution of that command happen at different times

UML Diagram

Command.jpg

Participants

Command

  • declares an interface for executing an operation.

ConcreteCommand (PasteCommand, OpenCommand)

  • defines a binding between a Receiver object and an action.
  • implements Execute by invoking the corresponding operation(s) on Receiver.

Client (Application)

  • creates a ConcreteCommand object and sets its receiver.

Invoker (MenuItem)

  • asks the command to carry out the request.

Receiver (Document, Application)

  • knows how to perform the operations associated with carrying out a request. Any class may serve as a Receiver.
Personal tools