← Back to Home

Memento Pattern

Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to that state later.

What is it?

The Memento pattern lets you save and restore the previous state of an object without revealing its implementation.

Example

class Memento {
  constructor(private readonly state: string) {}
  getState(): string {
    return this.state;
  }
}

class TextEditor {
  private content = '';

  type(words: string) {
    this.content += words;
  }

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

  save(): Memento {
    return new Memento(this.content);
  }

  restore(memento: Memento) {
    this.content = memento.getState();
  }
}

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

  add(memento: Memento) {
    this.mementos.push(memento);
  }

  undo(): Memento | null {
    return this.mementos.pop() || null;
  }
}

// Usage
const editor = new TextEditor();
const history = new History();

editor.type("Hello ");
history.add(editor.save());

editor.type("World!");
history.add(editor.save());

editor.restore(history.undo()!); // Undo last change

Common Uses

  • Undo/Redo systems
  • Form state management
  • Versioning tools

When to Use

  • Need to restore previous object state
  • Don’t want to expose internal details

Caution

  • Can use a lot of memory with large snapshots
  • Restoring logic must be reliable