Strategy lets you swap algorithms at runtime. Command encapsulates a request as an object, enabling undo, queuing, and logging of operations.
// 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