Deep Dive
low level designdesign patternsoop

Memento Pattern: Undo Without Cracking the Object Open

Every undo, savepoint, and game save has the same problem — capture an object's private state so you can restore it later, without letting the thing holding the snapshot read or corrupt what's inside.

·14 min read
Medium

The most requested feature in the history of software is Ctrl+Z. It is also the one most likely to be built wrong.

The naive version leaks everywhere. To undo a text edit, the “history” object needs the document’s contents — so you expose a public getter for the buffer, the caret, the selection, the dirty flags. Now the undo manager reaches into the editor’s guts, the editor can’t change its internal representation without breaking history, and worse: because history holds references to live state, an edit two seconds from now silently corrupts the snapshot you took two seconds ago. Your undo stack is full of aliases to the present.

The problem isn’t undo. It’s that capturing state and owning state got tangled together. You wanted a photograph; you took a live wire. The Gang of Four named the fix.

The intuition: a save point in a video game

Think about saving in a video game. You hit “save,” and the game writes a file: your position, inventory, quest flags — a frozen record of this exact moment. Later you “load,” and the game reads that file back into itself. Two things are true and both matter. First, the save file is opaque — you can’t open it in Notepad and edit your gold to 9,999 (well, not without cheating tools; that’s the whole point of it being sealed). Second, the game wrote it and the game reads it — the save-slot menu just holds a list of files. It never interprets them.

That save file is a memento. The game is the originator. The save-slot menu — the thing that holds your list of saves and lets you pick one — is the caretaker. Ctrl+Z is the same shape: each keystroke pushes a save file onto a stack, and undo loads the one below.

The two-interface trick is where this pattern earns its keep, and that’s exactly where the members-only walkthrough picks up: the three roles diagrammed out, annotated class boxes, the enforcement code in four languages, a traced Ctrl+Z, the snapshot-vs-command memory tradeoff every real editor faces, the interview corner, and a quiz to check yourself.

Members only

Keep reading with Premium

You've reached the members-only part of this deep-dive — the full implementation, the interactive ring simulator, and the step-by-step walkthrough. Unlock it with a membership.

Related Articles