Strategy lets you swap algorithms at runtime. Command encapsulates a request as an object, enabling undo, queuing, and logging of operations.
Strategy lets you swap algorithms at runtime. Command encapsulates a request as an object, enabling undo, queuing, and logging of operations.
Strategy and Command is one of the most important topics in Design Patterns in 5 Days. This lesson builds the foundation you need before moving to more advanced concepts — take time with each example and run the code yourself.
// Strategy — swappable sorting/pricing algorithms
interface SortStrategy<T> { sort(items: T[]): T[];
}
class AlphabeticalSort implements SortStrategy<string> { sort(items: string[]) { return [...items].sort(); }
}
class ReversedSort implements SortStrategy<string> { sort(items: string[]) { return [...items].sort().reverse(); }
}
class Sorter<T> { constructor(private strategy: SortStrategy<T>) {} setStrategy(strategy: SortStrategy<T>) { this.strategy = strategy; } sort(items: T[]) { return this.strategy.sort(items); }
}
const sorter = new Sorter(new AlphabeticalSort());
sorter.sort(['banana', 'apple', 'cherry']); // ['apple', 'banana', 'cherry']
sorter.setStrategy(new ReversedSort());
sorter.sort(['banana', 'apple', 'cherry']); // ['cherry', 'banana', 'apple'] // Command — encapsulate operations with undo
interface Command { execute(): void; undo(): void;
}
class MoveCommand implements Command { private prevX: number; private prevY: number; constructor( private shape: Shape, private dx: number, private dy: number, ) { this.prevX = shape.x; this.prevY = shape.y; } execute() { this.shape.x += this.dx; this.shape.y += this.dy; } undo() { this.shape.x = this.prevX; this.shape.y = this.prevY; }
}
class CommandHistory { private history: Command[] = []; execute(cmd: Command) { cmd.execute(); this.history.push(cmd); } undo() { this.history.pop()?.undo(); }
}
const history = new CommandHistory();
history.execute(new MoveCommand(circle, 10, 0));
history.execute(new MoveCommand(circle, 0, 5));
history.undo(); // circle moves back Before moving on, make sure you can answer these without looking: