Skip to content

Design Patterns

Memento

Saving or restoring one snapshot takes O(n) time, where n is the size of the data you copy.

The idea, in plain English

A memento works like a save point in a video game. Before a tough boss fight, you save your progress. If things go wrong, you don't restart the whole game. You just load that save point and you're back where you were. In code, a memento is a stored snapshot of an object's data. You can restore it later — that's how undo works.

How it works

  1. 1The object you want to protect can make a 'memento' — a snapshot copy of its current data.
  2. 2You keep that memento somewhere safe: a variable, or a stack of past snapshots for multi-step undo.
  3. 3To undo, you hand the memento back to the object, and it copies that old data back over its current data.

When you'd use it

Use this when you want undo/redo, checkpoints, or the ability to roll back to an earlier state. Examples: text editors, games, or form drafts.

Common beginner mistakes

  • Save a real separate copy, not just a reference to the live object. Otherwise 'the snapshot' keeps changing along with the original.
  • Don't save a snapshot after every tiny change. Save at meaningful checkpoints, or you'll waste memory on saves nobody restores.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Before undo: Hello, world!
After undo: Hello

Not sure this is the right topic? See the learning paths → or where this leads →