Behavioral Patternshigh

Command Pattern

Encapsulate a request as an object, allowing you to parameterize clients with different requests, queue or log requests, and support undoable operations.

Memory anchor

Command = a restaurant order ticket. The waiter writes down 'one burger, no onions' (the command), pins it to the board (queue), and the cook (receiver) executes it later. You can even cancel the ticket (undo) before the grill fires.

Expected depth

A Command object contains the receiver reference, the action to perform, and any parameters. The invoker calls command.execute(); the client creates the command and wires receiver to command to invoker. The key power: execute() and undo() as first-class operations. Use cases: text editor operations (each keystroke is a command, undo stack pops commands), task queues (commands serialized and dispatched to workers), macro recording (record a list of commands, replay them).

Deep — senior internals

Command is the pattern of deferred execution. By encapsulating the action, you can: (1) Queue it for later execution; (2) Log it to disk for durability and replay; (3) Undo it by maintaining the previous state or a reverse command. Undo implementation: snapshot-based (save full state before execute — simple but memory-intensive) or inverse-based (store the inverse command — space-efficient but not always possible). Command is related to Memento (snapshot-based undo uses Memento to save state). In distributed systems, Command is the basis for the Command Query Responsibility Segregation (CQRS) pattern — write operations are commands, stored as events. This enables event sourcing: replay all commands to reconstruct state at any point in time.

🎤Interview-ready answer

Command is the pattern for undo/redo and queued execution. In a text editor: every user action (InsertTextCommand, DeleteTextCommand, FormatCommand) is a Command object with execute() and undo(). The editor maintains an undo stack. Ctrl-Z pops the top command and calls undo(). Ctrl-Y re-executes it. The same pattern works for distributed job queues: serialize the command object, push it to a queue, workers call execute(). I always discuss undo strategy: snapshot-based (save entire document state before each command — simple but O(n) space) vs inverse command (for InsertText('hello'), undo is DeleteText(position, 5) — O(1) space but requires computing the inverse).

Common trap

Command vs Strategy: both encapsulate behavior. Strategy encapsulates an interchangeable algorithm with no receiver — the context IS the receiver. Command encapsulates a specific action on a specific receiver — the command and receiver are separate. Commands are usually short-lived (one action); Strategies are usually long-lived (injected into a context and reused).

Related concepts