The Command Pattern
You'll learn how to wrap actions as objects so you can delay, queue, or reverse them.
What Is the Command Pattern?
The Command Pattern turns a request or action into a stand-alone object that contains all the information needed to perform that action. Instead of directly calling a method, you create a command object that knows how to execute (and often undo) the operation.
Think of it like a remote control button. The button doesn't directly control your TV—it sends a command object that carries instructions. That command can be stored, logged, queued, or even reversed.
Core Structure
A command typically has:
execute()method: performs the actionundo()method (optional): reverses the action- State: stores parameters needed for execution
Simple Example
// Receiver: the object that does the actual work
const light = {
on() { console.log('Light is ON'); },
off() { console.log('Light is OFF'); }
};
// Command objects
const turnOnCommand = {
execute: () => light.on(),
undo: () => light.off()
};
const turnOffCommand = {
execute: () => light.off(),
undo: () => light.on()
};
// Invoker: triggers commands
const remote = {
history: [],
press(command) {
command.execute();
this.history.push(command);
},
undoLast() {
const command = this.history.pop();
if (command) command.undo();
}
};
remote.press(turnOnCommand); // Light is ON
remote.press(turnOffCommand); // Light is OFF
remote.undoLast(); // Light is ON
Why Use It?
- Undo/redo functionality becomes trivial (store history)
- Queue actions to execute later
- Log or replay operations
- Decouple the requester from the executor
Key Takeaway: The Command Pattern encapsulates actions as objects, enabling powerful features like undo, queueing, and action history with minimal coupling between components.