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; restore() takes one back. The mistake in between simply disappears.

{ ...this } copies the object's field values into a new object. That copy matters: if the snapshot were the object itself, every later edit would change the “old state” too. For state that holds nested objects or arrays, use structuredClone(this) — a spread copies only the top level.

Save, break, restore

The snapshot was taken while the text was Hello, world!. After the bad edit the editor prints Hello, wrold! oops, and then restore(saved) brings the exact old text back — the holder of the snapshot never looked inside it.

Prompt
Write a TypeScript program with the Memento pattern: an Editor class with a text field, a Snapshot type with a readonly text field, a save method returning a snapshot made with a spread copy 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: TypeScript file and captured output

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 an array for multi-level undo; marking their fields readonly keeps holders from editing them.

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.