Behavioral Snapshot Token

Memento

Memento is a behavioral pattern that captures an object's internal state into a separate snapshot object, so that state can later be restored without any outside code ever seeing what the snapshot contains.

Complexity
Popularity

Problem

A vector-graphics app needs undo: before every move, resize, or color change, it should remember how the shape looked a moment ago. The obvious approach is to have the undo manager reach into the shape and copy out its fields.

That forces the shape to expose everything an outside snapshot-taker might ever need - position, dimensions, fill, stroke, z-order - as public fields or getters. The shape's internals are now part of its public contract, so refactoring its internal representation later means also rewriting the undo manager. And every new property added to the shape has to be remembered by whoever is copying it from outside.

Solution

Memento moves the job of taking a snapshot inside the object that owns the state - the originator. Since the originator already has full access to its own fields, it can package a private copy of them into a memento object and hand that memento back to whoever asked for it.

The memento itself is opaque to everyone except the originator that created it: outside code can hold onto it, store it, or pass it back later to be restored, but it can't peek inside or modify what it holds. The object responsible for keeping a history of these mementos - the caretaker - never needs to know what a shape's position or fill color actually is; it just archives snapshots and returns them on request.

When to Use

  • Reach for Memento when you need to capture and later restore an object's state - undo stacks, rollback points, checkpoints.
  • Use it when the only way to grab that state from outside the object would mean exposing fields that should stay implementation detail.

Real-World Examples

  • **Ctrl+Z in editors** - word processors and design tools like Figma snapshot the document before each edit so changes can be stepped back through.
  • **SQL SAVEPOINT** - a database transaction marks a savepoint it can roll back to without discarding the whole transaction.
  • **Git stash** - Git packs away the working tree's current state as an opaque commit-like object you can reapply later.