Skip to main content

What It Is

The Memento pattern saves a snapshot of an object's state so it can be restored later — without showing the object's insides to anyone. The object itself makes the snapshot and itself restores from it; the outside world just holds the snapshots.

This is the pattern behind "undo to a saved point", drafts, and checkpoints.


Example: Editor Snapshots

save() returns a snapshot — a frozen dataclass its holder cannot edit; restore() takes one back. The mistake in between simply disappears.

Save, break, restore

The snapshot was taken while the text was good. After the bad edit, restore(saved) brings the exact old state back — the holder of the snapshot never looked inside it.

Prompt
Write a Python program with the Memento pattern: an Editor with a text field, a frozen Snapshot dataclass, a save method returning a snapshot and a restore method taking one. Write good text, save, make a bad edit, print it, restore the snapshot and print the recovered text.
Output: complete Python program

When to Use It

Use it for checkpoints and rollback: editor undo, game saves, "restore defaults", transactional steps that may need reverting.

Skip it when the state is one or two plain values — just keep the old value in a variable. And compare with Command: commands undo step by step, mementos jump back to a saved point.


Pros and Cons

Pros: real rollback without exposing internals; snapshots are simple values that can be kept in lists for multi-level undo.

Cons: snapshots of big state cost memory fast; deciding what belongs in the snapshot (and keeping it complete as the class grows) is easy to get wrong.