Command Pattern
Command Pattern
Section titled “Command Pattern”Introduction
Section titled “Introduction”The Command pattern turns a request into a standalone object that contains all information about the request.
Implementation
Section titled “Implementation”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(); }}
// Usageconst 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 characterSummary
Section titled “Summary”- Encapsulates actions as objects
- Enables undo/redo, queuing, logging
- Good for text editors, game actions, transaction systems