Skip to main content

Sign in to CleanKata

Track your progress, earn XP, and unlock every lesson.

By signing in you agree to our Terms of Use and Privacy Policy.

Design Patterns80 XP8 min

Memento: Undo with Snapshots

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

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.

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.

🔧 Some exercises may still have errors. If something seems wrong, use the Feedback button (bottom-right of the page) to report it — it helps us fix it fast.

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

✗ Your version

Memento: Undo with Snapshots — CleanKata — CleanKata