Command
Wrap a request as an object β then queue it, log it, undo it, or retry it. The invoker never knows what it's actually triggering.
Intent & Description
π― Intent
Turn an action into a first-class object so it can be stored, passed around, queued, and reversed.
π Context
You need undo/redo in a text editor, a job queue for background tasks, macro recording, or transactional operations that might need rollback. Calling methods directly makes all of these impossible.
π‘ Solution
Encapsulate each operation as a Command object with an execute() method (and optionally undo()). An Invoker holds and fires Commands without knowing their implementation. Commands can be stored in a history stack, serialized, queued, or replayed.
Real-world Use Case
Source
π TL;DR
Action becomes an object. Objects can be queued, stored, undone, and replayed. Essential for undo/redo and job queues. Overkill if you just need to call a function.
Advantages
- Decouples who triggers an operation from who implements it β swap implementations freely.
- Compose simple commands into complex macros or transactions.
- Built-in support for undo/redo by maintaining a command history stack.
Disadvantages
- Adds a layer of indirection that can feel heavy for simple fire-and-forget actions.
class Command {
execute() {}
}
class SimpleCommand extends Command {
constructor(payload) { super(); this.payload = payload; }
execute() {
console.log(`SimpleCommand: Processing payload (${this.payload})`);
}
}
class Invoker {
setOnStart(command) { this.onStart = command; }
run() { this.onStart.execute(); }
}