Skip to main content
Design Patterns 80 XP · 8 min

Memento: Undo with Snapshots

Capture and restore an object's internal state without violating encapsulation — implement Undo by storing snapshots of past states.

Showing
Ad (728×90)

Why this matters

The naive approach to undo is to expose all of an object's fields so that external code can save and restore them. But this breaks encapsulation — every client now depends on the object's internals. Add a field, and the undo system silently breaks. The Memento pattern solves this elegantly: the object itself creates a snapshot (Memento) that is opaque to the outside. External code stores and returns the snapshot, but never inspects it.

The problem

Bad

The solution

Good

Memento vs Command for undo

Both patterns enable undo, but differently. Command stores the inverse operation — to undo "type Hello" it deletes "Hello". Memento stores a full snapshot — restoring is always a simple replacement. Command is more memory-efficient for small changes; Memento is simpler to implement correctly when state is complex or there's no clean inverse. Use Command when the inverse is obvious; Memento when it isn't.

Key takeaway

Memento's key insight: the originator (Editor) creates its own snapshot — no external code needs to read its private state to implement undo.

Done with this lesson?

Mark it complete to earn XP and track your progress.