BehavioralTypeScriptverifiedVerified

Memento Pattern in TypeScript

Captures and externalizes an object's internal state without violating encapsulation, allowing the object to be restored to that state later.

How to Implement the Memento Pattern in TypeScript

1Step 1: Define the Memento that captures editor state

class EditorMemento {
  constructor(
    private readonly content: string,
    private readonly cursor: number
  ) {}

  getContent(): string { return this.content; }
  getCursor(): number { return this.cursor; }
}

2Step 2: Implement the Editor with save and restore

class Editor {
  private content = "";
  private cursor = 0;

  type(text: string): void {
    this.content =
      this.content.slice(0, this.cursor) +
      text +
      this.content.slice(this.cursor);
    this.cursor += text.length;
  }

  save(): EditorMemento {
    return new EditorMemento(this.content, this.cursor);
  }

  restore(memento: EditorMemento): void {
    this.content = memento.getContent();
    this.cursor = memento.getCursor();
  }

  toString(): string {
    return `"${this.content}" (cursor: ${this.cursor})`;
  }
}

3Step 3: Create a History caretaker to manage snapshots

class History {
  private mementos: EditorMemento[] = [];

  push(memento: EditorMemento): void {
    this.mementos.push(memento);
  }

  pop(): EditorMemento | undefined {
    return this.mementos.pop();
  }
}

4Step 4: Take snapshots and undo changes

const editor = new Editor();
const history = new History();

history.push(editor.save());
editor.type("Hello");
history.push(editor.save());
editor.type(", World");

console.log(editor.toString()); // "Hello, World" (cursor: 12)

editor.restore(history.pop()!);
console.log(editor.toString()); // "Hello" (cursor: 5)

editor.restore(history.pop()!);
console.log(editor.toString()); // "" (cursor: 0)

Memento Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Memento Pattern in the Real World

Think of a video game save point. When you save, the game (originator) packages your character's stats, inventory, and position into a save file (memento). The save system (caretaker) stores these files without understanding their contents. When you die and reload, the save file is handed back to the game, which restores everything exactly as it was.