Command Pattern
Encapsulate a request as an object — parameterize clients with queues, requests, and operations.
📌 Key IdeaTurn an action into an object with
execute() / undo(). Invoker triggers; Receiver does real work. Enables macro recording, job queues, undo stacks, transactional behaviour.Visual
📦 Invoker ─▶ Command ─▶ Receiver
button.onClick(new PasteCommand(editor)) queue.submit(new SendEmailCommand(...)) // jobs
Decouples who triggers from what runs — command is first-class data.
When to Use
- You need undo/redo — stack commands or paired reversals.
- Schedule, queue, or log operations (audit trail).
- GUI actions as objects (
Action,Runnable, SwingAction). - Transactional semantics — compose commands.
When NOT to Use
- Trivial one-line calls with no undo/queue — pattern weight not worth it.
Anti-Pattern (What NOT to Do)
Huge switch on string actionBadjava
void onAction(String a) {
switch(a) { case "paste": ... } // no undo, no queueActions aren't objects — hard to extend.
The Right Way
Command objectsGoodjava
interface Command { void execute(); void undo(); }
class PasteCommand implements Command {
private final Editor e;
public void execute() { e.paste(); }
public void undo() { e.deletePaste(); }
}Invoker stores history for undo.
Pros & Cons
👍 Pros
- Macro transactions and composite commands.
- Clean separation invoker / receiver.
- Natural fit for message queues and event sourcing snapshots.
👎 Cons
- Many small classes — boilerplate.
Common Confusions Cleared Up
Command vs Strategy
Both encapsulate algorithms. Strategy varies algorithm family for one context (pluggable policy). Command encapsulates requests as objects — emphasis on invocation timing, queuing, undo — different narrative.
Interview Q&A
Likely Follow-up Questions
- CQS / event sourcing — relationship to Command?
Quick Cheat Sheet
IntentRequest as object; undo; queue.
ActorsInvoker, Command, Receiver.
vs StrategyRequest lifecycle vs algorithm swap.