Memento pattern
The memento pattern captures an object's internal state as an opaque snapshot and restores it later, enabling undo and rollback without breaking encapsulation.
Introduction
The Memento pattern lets an object expose a snapshot of its state without exposing the details of how that state is represented. The object that owns the state creates and restores the snapshot, while another object can store it for undo, redo, or checkpointing.
TL;DR / mental model
Think βsave a checkpoint, store it opaquely, and hand it back later.β The originator understands the snapshot; the caretaker only manages when to save and restore it.
The Problem It Solves
You are building a document editor with undo. The naive approach: let the undo manager reach into the document's private fields and copy them.
Two problems. First, NaiveUndoManager depends on every private field, so any change to the document's internals breaks the undo system. Second, the snapshot is a raw Map<String, Object> with no type safety, and nothing prevents other code from reading or mutating it.
Here is what changes when you apply the Memento pattern.
Structure
Three distinct roles. DocumentEditor (originator) knows how to snapshot and restore its own state. DocumentMemento (memento) is an immutable capsule; its contents are meaningful only to the originator. HistoryManager (caretaker) stores mementos in undo/redo stacks without ever inspecting the contents.
Implementation
The originator owns the save/restore logic. The caretaker only manages the stack. Memento fits when an object has complex internal state and needs checkpointing without exposing those internals.
Immutable mementos
Make the memento class immutable. If a caretaker could modify a stored snapshot, restoring it would produce corrupted state. Use final fields or Java records.
Continue Reading with Premium
Unlock this article and every other in-depth system design guide on the platform with SDEpedia Premium.
Related Articles
The command pattern turns requests into objects so you can queue, log, and undo operations. Decouple sender from receiver by encapsulating actions.
The state pattern encapsulates state-specific behavior into separate objects, eliminating large switch statements and making each state's logic independently testable.
Learn the five SOLID principles by building a real order-processing system in Java, with before and after code for every principle.