Command

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. Use when you want to parameterize objects by an action to perform, specify or queue requests at different times, or support undo/redo.

Examples:

  • A text editor has toolbar buttons, context menu items, and keyboard shortcuts that all trigger the same Copy operation. Instead of each UI element implementing copy logic directly, a CopyCommand object encapsulates the action; the same command is wired to every trigger, can be placed in a history stack for undo/redo, and queued for later execution.
class Command {
public:
  virtual void Execute() = 0;
};
class PasteCommand : public Command {
  Document* doc;
public:
  void Execute() override { doc->Paste(); }
};
class Invoker { // e.g. MenuItem
  Command* cmd;
  void Click() { cmd->Execute(); }
};

Synonyms: action, transaction