Skip to content

Command Pattern

The Command pattern turns a request into a standalone object that contains all information about the request.

class Command {
constructor(execute, undo) {
this.execute = execute;
this.undo = undo;
}
}
class CommandManager {
constructor() {
this.history = [];
}
execute(command) {
command.execute();
this.history.push(command);
}
undo() {
const command = this.history.pop();
if (command) command.undo();
}
}
// Usage
const manager = new CommandManager();
const addChar = new Command(
() => console.log('Added character'),
() => console.log('Undo add character')
);
manager.execute(addChar);
manager.execute(addChar);
manager.undo(); // Undo add character
  • Encapsulates actions as objects
  • Enables undo/redo, queuing, logging
  • Good for text editors, game actions, transaction systems