Memento Pattern
Keep an opaque state snapshot so the original object can restore itself without exposing its internals to history management.
· Last updated: 2026-11-07 · 8 min read
Overview
Returning to the state before an edit requires keeping the earlier content somewhere. If the history code reads each of the editor's internal fields and fills them back in itself, every new field drags a matching copy routine into the history side. So a change to how the editor is structured breaks the history code as well.
A Memento holds a state snapshot. The originator saves and restores its own state, while a caretaker retains the snapshot without interpreting its contents.
UML
The UML shows that split. TextEditor creates a private Snapshot and hands it over as ISnapshot. The caretaker holds that handle and gives it back at restore time, while TextEditor remains the side that actually reads and writes the state. ISnapshot is just a handle to be handed back.
History
GoF cataloged Memento as a behavioral pattern in Design Patterns in 1994. It captures restorable state while preserving the object encapsulation.1
Why use it?
The history code does not need to know how the editor represents its state. Even when there is more state to copy, it is handled inside the originator's own save and restore code. The caretaker's job is to stack snapshots and hand them back.
Because snapshots keep piling up and consume memory, decide up front how many to keep, how long they live, and how far back a restore should reach. Lifetime is when a snapshot gets dropped; reach is how many steps back a restore may go. Restoring a snapshot is also not expected to undo mail that has already been sent or changes made in external storage.
Example
The sequence is short. Save a draft, change the text, then restore the state you saved.
In the C# code, Save() creates a new Snapshot holding the editor's current string and owner identifier. If the string is "draft" at that point, a later Write("edited") leaves the existing snapshot holding "draft". Separating the live editor from the saved point gives restoration a previous state to return to.
Restore(saved) checks that the snapshot belongs to this editor, then assigns the saved string to the current Text. The caller never extracts the saved string and overwrites the editor directly; the editor interprets its own snapshot. The output True reports successful restoration, and draft shows the restored content.
using System;
using System.Collections.Generic;
using System.Linq;
var editor = new TextEditor();
editor.Write("draft");
ISnapshot saved = editor.Save();
editor.Write("edited");
Console.WriteLine(editor.Restore(saved));
Console.WriteLine(editor.Text);
interface ISnapshot { }
// Keep interpretation and restoration of saved state inside the original editor.
sealed class TextEditor
{
private readonly Guid id = Guid.NewGuid();
private sealed record Snapshot(Guid Owner, string Text) : ISnapshot
{
// A record's default ToString prints its property values, so hide them.
public override string ToString() => nameof(ISnapshot);
}
public string Text { get; private set; } = "";
public void Write(string text) => Text = text;
// Expose the snapshot through its common interface; the original editor interprets its private representation.
public ISnapshot Save() => new Snapshot(id, Text);
public bool Restore(ISnapshot snapshot)
{
if (snapshot is not Snapshot saved || saved.Owner != id) return false;
Text = saved.Text;
return true;
}
}
True
draftThe caller stores ISnapshot and later gives it back to TextEditor. TextEditor reads the string from the snapshot and restores the editor's state.
An extended example
The example checks the originator identifier and rejects a snapshot handed to a different editor.
using System;
using System.Collections.Generic;
using System.Linq;
var editor = new TextEditor();
editor.Write("draft");
ISnapshot saved = editor.Save();
var other = new TextEditor();
other.Write("other");
Console.WriteLine(other.Restore(saved));
Console.WriteLine(other.Text);
editor.Write("edited");
Console.WriteLine(editor.Restore(saved));
Console.WriteLine(editor.Text);
interface ISnapshot { }
// Keep interpretation and restoration of saved state inside the original editor.
sealed class TextEditor
{
private readonly Guid id = Guid.NewGuid();
private sealed record Snapshot(Guid Owner, string Text) : ISnapshot
{
// A record's default ToString prints its property values, so hide them.
public override string ToString() => nameof(ISnapshot);
}
public string Text { get; private set; } = "";
public void Write(string text) => Text = text;
// Expose the snapshot through its common interface; the original editor interprets its private representation.
public ISnapshot Save() => new Snapshot(id, Text);
public bool Restore(ISnapshot snapshot)
{
if (snapshot is not Snapshot saved || saved.Owner != id) return false;
Text = saved.Text;
return true;
}
}
False
other
True
draftA snapshot from a different originator returns false and leaves the receiving editor unchanged. Deciding which snapshot to accept is likewise the originator's call. What the example restores is only the in-memory state of a single string, and saving snapshots to a file or keeping versions compatible remains a separate problem.
TypeScript example
The history manager stores snapshots, and TextEditor reads their contents to restore its state. This lets the history manager retain past states without access to the editor's internal string.
type ISnapshot = Readonly<{ kind: "snapshot" }>;
// Keep interpretation and restoration of saved state inside the original editor.
class TextEditor {
#text = "";
readonly #snapshots = new WeakMap<ISnapshot, string>();
get text(): string { return this.#text; }
write(text: string): void { this.#text = text; }
// Return only a storage token and retain the actual text privately.
save(): ISnapshot {
const token = Object.freeze({ kind: "snapshot" as const });
this.#snapshots.set(token, this.#text);
return token;
}
restore(snapshot: ISnapshot): boolean {
const text = this.#snapshots.get(snapshot);
if (text === undefined) return false;
this.#text = text;
return true;
}
}
const editor = new TextEditor();
editor.write("draft");
const saved = editor.save();
editor.write("new");
console.log(editor.restore(saved));
console.log(editor.text);
console.log(new TextEditor().restore(saved));true
draft
falseIn TypeScript, the inside of the snapshot is hidden behind an immutable token and an editor-private WeakMap. Mimicking only the token's outward shape, or passing another editor's token, still restores nothing.
Dual interfaces (narrow vs. wide) and the trade-off with Command undo
What separates a true Memento from a public state DTO is its dual interface. GoF specified that a memento must present a narrow interface (such as the opaque ISnapshot handle) to the Caretaker—which may store and return the token but never inspect or tamper with its contents—while exposing a wide interface exclusively to the Originator (TextEditor) that created it. In C# a nested private sealed record Snapshot : ISnapshot enforces this boundary at compile time; in TypeScript an unexported WeakMap keyed by frozen tokens achieves the same encapsulation.
When designing undo/redo, weigh full-state Memento snapshots against incremental inverse operations in the Command Pattern. Whenever an operation is lossy or hard to invert—such as a floating-point image filter, a physics step, or a bulk formatting pass—restoring a saved Memento is far safer than trying to compute an exact mathematical inverse. Conversely, snapshotting a multi-megabyte document on every keystroke will exhaust memory rapidly; in those editors, combine incremental command deltas with periodic Memento checkpoints or immutable data structures that share unchanged subtrees.
Related reading
Footnotes
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994). Publisher record. Behavioral patterns, Memento. ↩