Memento Pattern

Save an object's state in a sealed snapshot that only the object itself can read back, so undo and rollback do not expose its internals.

Overview

The problem: undo without opening the box

A text editor needs undo. Somewhere, the state before each edit must be kept: the text, the cursor position, the selection. The undo code (a history list) needs to save and restore that state, but the editor should not have to expose its fields to do it. The moment the history can read and write the editor's internals, every other class can too.

There are three ways to get undo, and all three work. They differ in whether the editor's internals stay hidden and in what that costs.

  • Public getters and setters for every field: undo works, but nothing stays hidden. Anyone can now set the cursor past the end, so the editor's invariants leak.
  • The history keeps a deep copy of the whole editor: undo works and the internals stay hidden, but the copy takes the undo history too if that lives inside the editor. It is wasteful and easy to get wrong.
  • A sealed snapshot the editor creates and reads back: undo works and the internals stay hidden, at the cost of one small class.

The third approach is the Memento pattern.

Interview questions

  • Show the smell Memento fixes, and the fix.
  • Mementos are eating memory. What are your options?
  • How do you add redo?
  • What breaks a memento, and how do you guard against it?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio