ProgramGuru

Command Pattern

Command: start from the problem

See the responsibilities

InvokerKeeps a command
CommandCarries action and parameters
ReceiverOwns document state
UndoUses the action’s recorded identity
Invoker: Keeps a command → Command: Carries action and parameters → Receiver: Owns document state → Undo: Uses the action’s recorded identity

An editor needs to record a user’s action and offer undo. Passing raw callbacks around can lose the identity and state needed to reverse a particular local action.

This is a behavioral pattern lesson. Follow the responsibilities, inspect the small JavaScript example and compare the design choices. The example is local teaching code; its boundary is explained before you apply the idea to a real service.

What you’ll learn

  • Explain the problem Command addresses and the roles involved.
  • Follow the example and distinguish this pattern from nearby alternatives.
  • Choose when the benefit justifies the extra responsibilities and testing.

How the responsibilities work

Command represents an action as an object with an execution contract. The object can carry parameters and, where appropriate, information for a reversible local operation. An invoker can store or schedule commands without depending on each action’s implementation.

Our AddLine command records one local edit and can undo that edit by identity. Storing an object in memory does not make a durable task queue, and undoing an edit is not the same as refunding a payment.

Follow a small example

Read the JavaScript from top to bottom and compare the expected output. The values are chosen to make this pattern’s responsibility visible. This example runs in one local execution context; it does not create remote services, durable storage or production access controls.

JavaScript · local teaching example

const lines = [];
const command = {
  line: {id: 'L1', text: 'Hello'},
  execute() { if (!lines.some(x => x.id === this.line.id)) lines.push(this.line); },
  undo() { const i = lines.findIndex(x => x.id === this.line.id); if (i >= 0) lines.splice(i, 1); }
};
command.execute();
console.log(lines.length);
command.undo();
console.log(lines.length);

Expected output

1
0

Choose a design and inspect the consequence

Compare the design choices

A command is delivered twice.
Another user edited the document before undo.

Compare the visible consequences. With JavaScript enabled, choose an option in each scenario to assemble your decision record.

This is an exploratory design exercise. It does not run infrastructure, measure capacity or replace the lesson’s quiz.

Use the consequences to explain your decision, including the simpler alternative.

Apply the pattern to two situations. Select one option in each situation to build a decision record. Every option and its consequence stays visible, and you can change your choices.

When it helps—and what it costs

Use it to represent meaningful actions for history, scheduling or a supported undo boundary. Define command identity and repeated-execution behaviour.

An undo contract must account for intervening changes and irreversible effects. Stored commands can include sensitive parameters. Durable execution requires persistent progress and recovery, not merely a class with execute.

Distinguish the neighbouring patterns

Memento stores a state snapshot. Command stores an action. Saga compensation performs explicit new business actions across owners and may not perfectly reverse an effect.

Follow state snapshots for local history, compensating business effects, durable work delivery to compare the specific responsibility before combining patterns.

Check your pattern reasoning

What does the command object represent?
Choose one answer. You can try again.

Answer and explanation

An action with its parameters and execution rule.

The invoker can treat it through a common contract.

Check your pattern reasoning

Is undo universally safe for external effects?
Choose one answer. You can try again.

Answer and explanation

No; reversal depends on a specific contract.

A local edit and an external charge have different boundaries.

Name the responsibility before choosing the pattern

For Command, describe the problem, the participating roles and the observable contract. Use the example as a starting point and test the boundaries identified in the trade-offs. A pattern name alone does not establish correctness or performance.

Return to the design-pattern guide to compare families, or apply the idea alongside durable work delivery.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Template Method Pattern →