Day 4 of 5

Strategy and Command

Strategy lets you swap algorithms at runtime. Command encapsulates a request as an object, enabling undo, queuing, and logging of operations.

typescript
// 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']
typescript
// 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

Exercise: Build a Text Editor with Undo

  1. Create a TextEditor class with insert/delete methods
  2. Wrap each operation in a Command object
  3. Use CommandHistory to execute and undo commands
  4. Implement redo by keeping a redo stack
  5. Add a keyboard shortcut: Ctrl+Z = undo, Ctrl+Y = redo

Day 4 Summary

Finished this lesson?