Behavioral Action Transaction

Command

Command is a behavioral pattern that wraps a request - the receiver, the action, and its arguments - into a self-contained object, so the request itself can be passed around, stored, and invoked independently of whatever triggered it.

Complexity
Popularity

Problem

Consider a drawing app where the same "delete shape" action can be triggered from a toolbar button, a keyboard shortcut, and a right-click menu - and where the app also needs to support undo.

If each UI element calls the deletion logic directly, that logic ends up duplicated in three places, and none of them has any record of what just happened, so undo has nowhere to hook in. Wiring undo support after the fact usually means threading extra state through every place that can trigger an action.

The real issue is that "what to do" and "how it got triggered" are tangled together, with no single object representing the action itself that could be stored, replayed, or reversed.

Solution

Command pulls the request itself out into its own object: everything needed to perform the action - which receiver to call, which operation, with which arguments - is captured behind a single `execute()` method.

The UI element that triggers the action no longer calls the receiver directly; it just holds a command object and calls `execute()` on it, without caring what that command actually does or which object ends up doing the work. Because the command is a real object rather than a bare function call, it can be stored in a history list, serialized to disk, handed to a queue for later execution, or paired with an `undo()` method that reverses whatever `execute()` did.

When to Use

  • Reach for Command when you want to hand an operation to something else - a button, a menu item, a scheduler - as a value, rather than hardcoding the call site.
  • It's a natural fit when requests need to be queued, delayed, retried, or dispatched to a worker rather than executed immediately in place.
  • Use it whenever the application must support reversing actions the user has taken, since each command can carry its own undo logic.

Real-World Examples

  • **`document.execCommand` and editor undo stacks** - rich-text editors represent formatting and edit operations as discrete command objects pushed onto a history stack for multi-level undo.
  • **GUI toolkit actions** - frameworks like Qt and Swing model menu items, toolbar buttons, and shortcuts as `QAction`/`Action` objects so the same command can be triggered from multiple UI entry points.
  • **Background job queues** - systems like Sidekiq, Celery, and Bull serialize a job's target method and arguments into a command-like payload that a worker process picks up and executes later.