Patterncore
Memento pattern
Also called Memento, Token, snapshot, saved state.
An object saves its internal state in a memento, an object that other code can store but cannot read. Later the object restores that state from the memento. Undo is the usual use.
- Family
- behavioral-design
- Intent
- Capture the internal state of an object in a separate object, so that the object can return to that state later, and do this without breaking its encapsulation.
- Also called
- Token
Intent
Capture the internal state of an object in a separate object, so that the object can return to that state later. Do this without breaking the encapsulation of the object.1 The separate object is the memento. Other code stores it and gives it back, but only the object that made it can read it.
Problem
Design Patterns starts with undo in a graphical editor. The user can move a shape that is connected to other shapes, and a constraint solver keeps the connections. To undo the move, the editor must put the shapes and the solver back as they were. The solver keeps internal state for this, and it does not make that state public.1
The same need appears in a text editor, a form with a cancel button, a game that saves a checkpoint, a transaction that rolls back, and a search that tries a move and takes it back.
The forces are these. Undo needs the earlier state. The earlier state is private to the object, and making it public breaks the object's encapsulation: the code that saves it then depends on its fields and can change them. And the code that decides when to save and when to restore, such as an undo stack, is not the object itself.
Solution
Design Patterns names three participants.1
- Originator is the object whose state is saved. It makes a memento of its current state, and it restores its state from a memento.
- Memento stores some or all of the internal state of the originator. It protects that state from all objects except the originator.
- Caretaker keeps the mementos. It never reads or changes the contents of a memento.
Design Patterns describes the memento as having two interfaces. The caretaker sees a narrow interface: it can only pass the memento on. The originator sees a wide interface: it can read all the data that it needs to restore itself.1
Caretaker (History) Originator (Editor)
undo stack: [m1, m2, m3] text, cursor (private)
| |
| save() -------------------> makes Memento(text, cursor)
| <------------------- m3 ---- (the caretaker cannot read m3)
|
| restore(m3) --------------> reads m3, sets text and cursor
Each example file builds a text editor and an undo history. The editor has text and a cursor. The history saves a memento before each edit, and undo restores the last one:
- Type
Hello. The editor showsHello|, where|is the cursor. - Type
world. The editor showsHello world|. - Move the cursor to 5 and type
,. The editor showsHello,| world. - Undo three times, back to the empty text. A fourth undo prints
nothing to undo.
A memento must not share mutable state
A memento must not change after it is made. When it holds a reference to a list or a dict that the originator keeps changing, it changes with the originator, and the undo restores the present state:
This code runs but gives a wrong answer on purpose.
class Editor:
def __init__(self):
self.lines = []
def add(self, line):
self.lines.append(line)
def save(self):
return self.lines # the memento is the live list, not a copy
def restore(self, memento):
self.lines = memento
editor = Editor()
editor.add("first")
saved = editor.save()
editor.add("second")
editor.restore(saved)
print(editor.lines)
['first', 'second']
The undo did nothing, because saved and editor.lines are one list. The fix is a copy when the memento is made: list(self.lines) for a list of strings, or copy.deepcopy for nested data.2 This is the same decision about shallow and deep copies that Prototype pattern needs. A field of the state that is immutable needs no copy: Python strings, Java strings, Go strings and C# strings cannot change, so a memento can share them.
Immutable state makes the memento free
When the whole state of the originator is an immutable value, the state is its own memento. Saving is storing a reference, and restoring is assigning one. A frozen dataclass in Python raises FrozenInstanceError on an attempt to set a field.3 dataclasses.replace makes a copy with some fields changed.4 A tuple of lines shares each line that did not change:
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Document:
lines: tuple[str, ...]
cursor: int
def edit_line(doc: Document, index: int, text: str) -> Document:
return replace(doc, lines=doc.lines[:index] + (text,) + doc.lines[index + 1 :])
history: list[Document] = []
doc = Document(lines=("title", "body", "footer"), cursor=0)
history.append(doc) # the snapshot is a reference: no copy
doc = edit_line(doc, 1, "body, edited")
history.append(doc)
doc = replace(doc, cursor=2)
saved = history[0]
shared = sum(a is b for a, b in zip(saved.lines, doc.lines))
print("now:", doc.lines, "cursor", doc.cursor)
print("lines shared with the first snapshot:", shared, "of", len(doc.lines))
while history:
doc = history.pop()
print("undo:", doc.lines, "cursor", doc.cursor)
now: ('title', 'body, edited', 'footer') cursor 2
lines shared with the first snapshot: 2 of 3
undo: ('title', 'body, edited', 'footer') cursor 0
undo: ('title', 'body', 'footer') cursor 0
The two snapshots and the present state share the strings "title" and "footer". Each edit allocates only what changed. The Redux documentation builds undo this way. The state shape holds an array of past states, the present state and an array of future states. Undo moves the present state to the future array and takes the last past state as the present.6 The state is never changed in place, so each entry in the arrays is a full snapshot that costs one reference.
Memento and Command for undo
Command pattern gives the other way to undo. Each command knows how to reverse itself: an insert command deletes what it inserted, and a move command moves back. A memento saves the state before the change, and an undo restores it.
The two differ in what they store. A command stores the change, which is small. A memento stores the state, which can be large. But a reverse operation is not always possible from the change alone. Here an editor makes text upper case, and the undo command makes it lower case:
This code runs but gives a wrong answer on purpose.
class UpperCase:
def execute(self, text):
return text.upper()
def undo(self, text):
return text.lower() # the reverse loses the original case
text = "Hello World"
command = UpperCase()
text = command.execute(text)
print("after:", text)
print("undo:", command.undo(text))
after: HELLO WORLD
undo: hello world
The upper-case operation loses information, so no reverse function exists. The command must save the earlier text before it runs, which is a memento. Design Patterns says that commands can use mementos to keep the state that undoable operations need.1 Most undo systems mix the two: commands for operations with a cheap exact reverse, and mementos for the rest.
Fowler describes the same choice for event sourcing. A system can reverse an event by applying its inverse. Or it can go back to an earlier snapshot of the state and replay the events after it, up to the point it wants.7
Serialization
A memento that must outlive the process, such as a saved game or a draft, is serialized to bytes. Python's pickle serializes most objects with no code in the class. The documentation warns that the module is not secure: unpickling data can run arbitrary code, so a program must never unpickle data from a source that it does not trust.5 A memento written to a file that a user can edit needs a format with no code in it, such as JSON, and a check of its contents on load. A browser's history.pushState is a caretaker of this kind. It adds an entry to the session history with a serialization of the state that the page gives it, and the page reads the state back when the user goes back.10
Example
The table shows how each language builds the narrow interface, so that the caretaker cannot read the memento.
| Language | Narrow interface |
|---|---|
| Python | a private nested class by convention, typed as object for the caretaker |
| JavaScript | an empty frozen object as a key into a private static WeakMap |
| TypeScript | a branded type with a unique symbol key |
| Java | a nested class with private fields and constructor |
| C# | an empty public interface and a private nested record |
| Go | a struct with unexported fields |
| Rust | a struct with fields private to the originator's module |
| C++ | a class with private members and the originator as a friend |
In Java, a private member is accessible from anywhere in the body of the top level class that encloses it.8 In Rust, a private item is visible in its module and the modules below it.9 So in Java the originator must be a top level class, and in Rust the memento must be in the originator's module, for the caretaker to be shut out.
from dataclasses import dataclass
class Editor:
"""The originator. Only it reads and writes the contents of a memento."""
@dataclass(frozen=True)
class _Memento:
text: str
cursor: int
def __init__(self):
self._text = ""
self._cursor = 0
def type(self, chars: str) -> None:
self._text = self._text[: self._cursor] + chars + self._text[self._cursor :]
self._cursor += len(chars)
def move_to(self, cursor: int) -> None:
self._cursor = max(0, min(cursor, len(self._text)))
def save(self) -> object:
return Editor._Memento(self._text, self._cursor)
def restore(self, memento: object) -> None:
if not isinstance(memento, Editor._Memento):
raise TypeError("not a memento of an Editor")
self._text, self._cursor = memento.text, memento.cursor
def show(self) -> str:
return self._text[: self._cursor] + "|" + self._text[self._cursor :]
class History:
"""The caretaker. It keeps mementos and never looks inside them."""
def __init__(self, editor: Editor):
self._editor = editor
self._undo: list[object] = []
def save(self) -> None:
self._undo.append(self._editor.save())
def undo(self) -> bool:
if not self._undo:
return False
self._editor.restore(self._undo.pop())
return True
editor = Editor()
history = History(editor)
history.save()
editor.type("Hello")
print(editor.show())
history.save()
editor.type(" world")
print(editor.show())
history.save()
editor.move_to(5)
editor.type(",")
print(editor.show())
for _ in range(4):
if history.undo():
print("undo:", editor.show())
else:
print("nothing to undo")
Hello|
Hello world|
Hello,| world
undo: Hello world|
undo: Hello|
undo: |
nothing to undo
- Verdict: idiom.
savereturns an object andrestoretakes one back. The caretaker types the memento asobject, so a type checker reports any attempt to read its fields. - Python has no access control. The leading underscore of
_Mementoand theobjecttype are conventions that tell the caretaker not to look inside. - The memento is a frozen dataclass, and both of its fields are immutable values. The memento needs no copy of the text, because a
strcannot change. copy.deepcopyof the originator's state is the general form when the state holds lists or dicts. The node page shows the bug when the memento keeps a reference to a list that the originator still changes.
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
class Editor;
// The memento. The caretaker can copy, move and destroy it, but only Editor
// can make one or read its state.
class Memento {
private:
friend class Editor;
Memento(std::string text, std::size_t cursor) : text_(std::move(text)), cursor_(cursor) {}
std::string text_;
std::size_t cursor_;
};
// The originator.
class Editor {
public:
void type(const std::string& chars) {
text_.insert(cursor_, chars);
cursor_ += chars.size();
}
void move_to(std::size_t position) { cursor_ = std::min(position, text_.size()); }
Memento save() const { return Memento(text_, cursor_); }
void restore(Memento memento) {
text_ = std::move(memento.text_);
cursor_ = memento.cursor_;
}
std::string show() const { return text_.substr(0, cursor_) + "|" + text_.substr(cursor_); }
private:
std::string text_;
std::size_t cursor_ = 0;
};
// The caretaker. It keeps mementos and cannot look inside them.
class History {
public:
explicit History(Editor& editor) : editor_(editor) {}
void save() { undo_.push_back(editor_.save()); }
bool undo() {
if (undo_.empty()) return false;
Memento memento = std::move(undo_.back());
undo_.pop_back();
editor_.restore(std::move(memento));
return true;
}
private:
Editor& editor_;
std::vector<Memento> undo_;
};
int main() {
Editor editor;
History history(editor);
history.save();
editor.type("Hello");
std::cout << editor.show() << '\n';
history.save();
editor.type(" world");
std::cout << editor.show() << '\n';
history.save();
editor.move_to(5);
editor.type(",");
std::cout << editor.show() << '\n';
for (int i = 0; i < 4; ++i) {
std::cout << (history.undo() ? "undo: " + editor.show() : "nothing to undo") << '\n';
}
}
Hello|
Hello world|
Hello,| world
undo: Hello world|
undo: Hello|
undo: |
nothing to undo
- Verdict: idiom. This is the form that Design Patterns describes for C++: the memento's state and constructor are
private, and the originator is afriend. The caretaker sees only the copy and move operations, which the compiler declares as public. savecopies thestd::string, because the copy constructor ofstd::stringcopies its characters. The memento owns its own text.restoretakes the memento by value, andundomoves it out of the vector, so the text is moved back into the editor with no second copy.
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
/** The originator. Only it reads and writes the fields of its mementos. */
static final class Editor {
/** The memento. Its fields and constructor are private, but Editor encloses it. */
static final class Memento {
private final String text;
private final int cursor;
private Memento(String text, int cursor) {
this.text = text;
this.cursor = cursor;
}
}
private String text = "";
private int cursor = 0;
void type(String chars) {
text = text.substring(0, cursor) + chars + text.substring(cursor);
cursor += chars.length();
}
void moveTo(int position) {
cursor = Math.max(0, Math.min(position, text.length()));
}
Memento save() {
return new Memento(text, cursor);
}
void restore(Memento memento) {
text = memento.text;
cursor = memento.cursor;
}
String show() {
return text.substring(0, cursor) + "|" + text.substring(cursor);
}
}
/** The caretaker. It keeps mementos and cannot read them. */
static final class History {
private final Editor editor;
private final Deque<Editor.Memento> undo = new ArrayDeque<>();
History(Editor editor) {
this.editor = editor;
}
void save() {
undo.push(editor.save());
}
boolean undo() {
Editor.Memento memento = undo.poll();
if (memento == null) return false;
editor.restore(memento);
return true;
}
}
public static void main(String[] args) {
Editor editor = new Editor();
History history = new History(editor);
history.save();
editor.type("Hello");
System.out.println(editor.show());
history.save();
editor.type(" world");
System.out.println(editor.show());
history.save();
editor.moveTo(5);
editor.type(",");
System.out.println(editor.show());
for (int i = 0; i < 4; i++) {
System.out.println(history.undo() ? "undo: " + editor.show() : "nothing to undo");
}
}
}
Hello|
Hello world|
Hello,| world
undo: Hello world|
undo: Hello|
undo: |
nothing to undo
- Verdict: idiom. A static nested class with
privatefields and aprivateconstructor. Java allows access to aprivatemember from anywhere in the body of the top level class that encloses it. Here that class isMain, soHistorycould read the fields too. In a real program,Editoris a top level class in its own file, and onlyEditorcan read them. Stringis immutable, so the memento stores the reference and needs no copy.- A
recordis a poor memento: its components have public accessor methods, so the caretaker could read the state. ArrayDeque.pushandpollgive a stack.pollreturnsnullon an empty deque, wherepopwould throw.
using System;
using System.Collections.Generic;
var editor = new Editor();
var history = new History(editor);
history.Save();
editor.Type("Hello");
Console.WriteLine(editor.Show());
history.Save();
editor.Type(" world");
Console.WriteLine(editor.Show());
history.Save();
editor.MoveTo(5);
editor.Type(",");
Console.WriteLine(editor.Show());
for (int i = 0; i < 4; i++)
{
Console.WriteLine(history.Undo() ? $"undo: {editor.Show()}" : "nothing to undo");
}
// The narrow interface. The caretaker sees a type with no members.
interface IMemento;
// The originator. Only it knows the type behind IMemento.
sealed class Editor
{
private sealed record Snapshot(string Text, int Cursor) : IMemento;
private string text = "";
private int cursor;
public void Type(string chars)
{
text = text[..cursor] + chars + text[cursor..];
cursor += chars.Length;
}
public void MoveTo(int position) => cursor = Math.Clamp(position, 0, text.Length);
public IMemento Save() => new Snapshot(text, cursor);
public void Restore(IMemento memento)
{
if (memento is not Snapshot snapshot)
throw new ArgumentException("not a memento of an Editor", nameof(memento));
(text, cursor) = (snapshot.Text, snapshot.Cursor);
}
public string Show() => text[..cursor] + "|" + text[cursor..];
}
// The caretaker. It keeps mementos and cannot read them.
sealed class History(Editor editor)
{
private readonly Stack<IMemento> undo = new();
public void Save() => undo.Push(editor.Save());
public bool Undo()
{
if (!undo.TryPop(out IMemento? memento)) return false;
editor.Restore(memento);
return true;
}
}
Hello|
Hello world|
Hello,| world
undo: Hello world|
undo: Hello|
undo: |
nothing to undo
- Verdict: idiom. An empty public interface is the narrow interface, and a
privatenested record that implements it is the wide one. Code outsideEditorcannot nameSnapshot, so it cannot cast to it. interface IMemento;with a semicolon and no body declares an empty interface.- A positional record is immutable, and
stringis immutable, so a snapshot needs no deep copy. Stack<T>.TryPopreturnsfalseon an empty stack, wherePopwould throwInvalidOperationException.
// The originator. Only it can read the state behind a memento.
class Editor {
static #states = new WeakMap(); // memento -> saved state, visible only inside Editor
#text = "";
#cursor = 0;
type(chars) {
this.#text = this.#text.slice(0, this.#cursor) + chars + this.#text.slice(this.#cursor);
this.#cursor += chars.length;
}
moveTo(cursor) {
this.#cursor = Math.max(0, Math.min(cursor, this.#text.length));
}
save() {
const memento = Object.freeze({}); // an opaque token for the caretaker
Editor.#states.set(memento, { text: this.#text, cursor: this.#cursor });
return memento;
}
restore(memento) {
const state = Editor.#states.get(memento);
if (state === undefined) throw new TypeError("not a memento of an Editor");
this.#text = state.text;
this.#cursor = state.cursor;
}
show() {
return this.#text.slice(0, this.#cursor) + "|" + this.#text.slice(this.#cursor);
}
}
// The caretaker. It keeps mementos and cannot look inside them.
class History {
#undo = [];
constructor(editor) {
this.editor = editor;
}
save() {
this.#undo.push(this.editor.save());
}
undo() {
if (this.#undo.length === 0) return false;
this.editor.restore(this.#undo.pop());
return true;
}
}
const editor = new Editor();
const history = new History(editor);
history.save();
editor.type("Hello");
console.log(editor.show());
history.save();
editor.type(" world");
console.log(editor.show());
history.save();
editor.moveTo(5);
editor.type(",");
console.log(editor.show());
for (let i = 0; i < 4; i++) {
console.log(history.undo() ? `undo: ${editor.show()}` : "nothing to undo");
}
Hello|
Hello world|
Hello,| world
undo: Hello world|
undo: Hello|
undo: |
nothing to undo
- Verdict: idiom. The memento is an empty frozen object, and the editor keeps the saved state in a private static
WeakMapkeyed by that object. Code outsideEditorcannot reach the state, even by reflection. - A
WeakMapdoes not keep its keys alive. When the caretaker drops a memento, the saved state can be collected with it. - The shorter form returns
Object.freeze({ text, cursor }). The caretaker can then read the fields, so the encapsulation rests on a convention, as in Python. structuredClonemakes a deep copy of a plain state object, which suits an originator whose state holds arrays or nested objects.
declare const mementoBrand: unique symbol;
// The narrow interface. The caretaker sees a type with no readable members.
type Memento = { readonly [mementoBrand]: "Editor" };
type State = { readonly text: string; readonly cursor: number };
// The originator. Only it turns a Memento back into a State.
class Editor {
#text = "";
#cursor = 0;
type(chars: string): void {
this.#text = this.#text.slice(0, this.#cursor) + chars + this.#text.slice(this.#cursor);
this.#cursor += chars.length;
}
moveTo(cursor: number): void {
this.#cursor = Math.max(0, Math.min(cursor, this.#text.length));
}
save(): Memento {
const state: State = Object.freeze({ text: this.#text, cursor: this.#cursor });
return state as unknown as Memento;
}
restore(memento: Memento): void {
const state = memento as unknown as State; // the wide interface, used only here
this.#text = state.text;
this.#cursor = state.cursor;
}
show(): string {
return this.#text.slice(0, this.#cursor) + "|" + this.#text.slice(this.#cursor);
}
}
// The caretaker. It keeps mementos and cannot read them without a cast.
class History {
readonly #undo: Memento[] = [];
readonly #editor: Editor;
constructor(editor: Editor) {
this.#editor = editor;
}
save(): void {
this.#undo.push(this.#editor.save());
}
undo(): boolean {
const memento = this.#undo.pop();
if (memento === undefined) return false;
this.#editor.restore(memento);
return true;
}
}
const editor = new Editor();
const history = new History(editor);
history.save();
editor.type("Hello");
console.log(editor.show());
history.save();
editor.type(" world");
console.log(editor.show());
history.save();
editor.moveTo(5);
editor.type(",");
console.log(editor.show());
for (let i = 0; i < 4; i++) {
console.log(history.undo() ? `undo: ${editor.show()}` : "nothing to undo");
}
Hello|
Hello world|
Hello,| world
undo: Hello world|
undo: Hello|
undo: |
nothing to undo
- Verdict: idiom. A branded type is the narrow interface.
Mementohas one member, keyed by aunique symbolthat no code can name outside its declaration, so the caretaker can store a memento but not read it. - The brand exists only in the type system. At run time the memento is the frozen state object, and the casts in
saveandrestoreare the one place where the two views meet. declare constemits no code, so Node.js type stripping accepts it.
package main
import "fmt"
// Memento holds a saved state. Its fields are unexported, so code in other
// packages can store a Memento but cannot read or change it.
type Memento struct {
text string
cursor int
}
// Editor is the originator.
type Editor struct {
text string
cursor int
}
func (e *Editor) Type(chars string) {
e.text = e.text[:e.cursor] + chars + e.text[e.cursor:]
e.cursor += len(chars)
}
func (e *Editor) MoveTo(position int) { e.cursor = max(0, min(position, len(e.text))) }
func (e *Editor) Save() Memento { return Memento{text: e.text, cursor: e.cursor} }
func (e *Editor) Restore(m Memento) { e.text, e.cursor = m.text, m.cursor }
func (e *Editor) Show() string { return e.text[:e.cursor] + "|" + e.text[e.cursor:] }
// History is the caretaker.
type History struct {
editor *Editor
undo []Memento
}
func (h *History) Save() { h.undo = append(h.undo, h.editor.Save()) }
func (h *History) Undo() bool {
if len(h.undo) == 0 {
return false
}
last := h.undo[len(h.undo)-1]
h.undo = h.undo[:len(h.undo)-1]
h.editor.Restore(last)
return true
}
func main() {
editor := &Editor{}
history := &History{editor: editor}
history.Save()
editor.Type("Hello")
fmt.Println(editor.Show())
history.Save()
editor.Type(" world")
fmt.Println(editor.Show())
history.Save()
editor.MoveTo(5)
editor.Type(",")
fmt.Println(editor.Show())
for range 4 {
if history.Undo() {
fmt.Println("undo:", editor.Show())
} else {
fmt.Println("nothing to undo")
}
}
}
Hello|
Hello world|
Hello,| world
undo: Hello world|
undo: Hello|
undo: |
nothing to undo
- Verdict: idiom. A struct with unexported fields is the narrow interface for code in other packages. In this one-file program everything is in package
main, so the fields are visible toHistorytoo. - The memento is a value, not a pointer.
Savereturns a copy of the fields, and Go strings are immutable, so the memento needs no deep copy. - A state that holds a slice or a map needs
slices.Cloneormaps.CloneinSave. A struct copy shares the backing array of a slice. TypeandShowindex the string by bytes. That is correct here because the text is ASCII.
mod editor {
/// The memento. Its fields are private to this module, so code outside
/// the module can hold a Memento but cannot read or build one.
pub struct Memento {
text: String,
cursor: usize,
}
/// The originator.
#[derive(Default)]
pub struct Editor {
text: String,
cursor: usize,
}
impl Editor {
pub fn type_text(&mut self, chars: &str) {
self.text.insert_str(self.cursor, chars);
self.cursor += chars.len();
}
pub fn move_to(&mut self, position: usize) {
self.cursor = position.min(self.text.len());
}
pub fn save(&self) -> Memento {
Memento { text: self.text.clone(), cursor: self.cursor }
}
/// Takes the memento by value: a restored memento is used up.
pub fn restore(&mut self, memento: Memento) {
self.text = memento.text;
self.cursor = memento.cursor;
}
pub fn show(&self) -> String {
format!("{}|{}", &self.text[..self.cursor], &self.text[self.cursor..])
}
}
}
use editor::{Editor, Memento};
/// The caretaker. It keeps mementos and cannot look inside them.
struct History {
undo: Vec<Memento>,
}
impl History {
fn save(&mut self, editor: &Editor) {
self.undo.push(editor.save());
}
fn undo(&mut self, editor: &mut Editor) -> bool {
match self.undo.pop() {
Some(memento) => {
editor.restore(memento);
true
}
None => false,
}
}
}
fn main() {
let mut editor = Editor::default();
let mut history = History { undo: Vec::new() };
history.save(&editor);
editor.type_text("Hello");
println!("{}", editor.show());
history.save(&editor);
editor.type_text(" world");
println!("{}", editor.show());
history.save(&editor);
editor.move_to(5);
editor.type_text(",");
println!("{}", editor.show());
for _ in 0..4 {
if history.undo(&mut editor) {
println!("undo: {}", editor.show());
} else {
println!("nothing to undo");
}
}
}
Hello|
Hello world|
Hello,| world
undo: Hello world|
undo: Hello|
undo: |
nothing to undo
- Verdict: idiom. Module privacy gives the narrow interface. A private field is visible in its module and the modules below it, so
Historyin the parent module cannot readmemento.text, and the compiler rejects any attempt. savemust clone theString, because the editor keeps its own.restoretakes the memento by value and moves the string back in, with no second copy.- The history passes
&Editorand&mut Editorin each call and holds no reference to the editor. A caretaker that held&mut Editorwould lock the editor for as long as the caretaker lives. insert_strand the slices index by bytes, and they panic at a position that is not on a character boundary. The text here is ASCII.
Consequences
Design Patterns lists these consequences.1
- It keeps encapsulation boundaries. The memento hides the originator's state from the caretaker, so other objects do not depend on it.
- It simplifies the originator. Without mementos, the originator would keep every version of its state for the clients that want them. The caretaker keeps them instead.
- Mementos can be expensive. A memento that copies a large state, or an originator that makes mementos often, costs memory and time. Design Patterns suggests that a memento can store only the change since the last one, when mementos are made and restored in a known order.
- Narrow and wide interfaces are hard in some languages. A language must let the originator, and no other class, read the memento. The table above shows how far each language gets.
- The cost of keeping mementos is hidden. The caretaker does not know how much state a memento holds, so a caretaker that looks cheap can hold a large amount of memory.
The last point needs a limit in practice. An undo stack with no limit grows for the life of the document. Editors cap the number of entries, merge small changes such as single key strokes into one entry, or drop old entries.
A memento also captures only the originator's own state. An object that refers to other objects must decide whether to save them too. A memento of the editor that does not save the clipboard restores the text but not the clipboard. A memento of a shape that refers to a shared style must not restore the style for other shapes.
When not to use it
Do not use it when the state is public and the class is a plain data record. A copy of the record is enough, and the narrow interface protects nothing.
Do not use it when each change has a cheap exact reverse and the state is large. A command that stores the change takes less memory than a snapshot of the whole state.
Do not use mementos to send state across a trust boundary, such as to a browser and back, unless the format is safe to parse and the originator checks it on restore. A memento from outside is input.
Do not build it by hand when the state is already immutable. The state value is the memento, and a list of references is the caretaker, as the block above shows.
Variants and related patterns
Command. Design Patterns says that commands can use mementos to keep state for undoable operations.1 A command saves a memento before it runs, and its undo restores it. See Command pattern.
Prototype. A prototype and a memento both copy the state of an object. A prototype copy is a new object that lives on its own. A memento is a saved state that its originator reads back, and no other code uses it as an object. See Prototype pattern.
State. A state object holds the behaviour of one state of a context, and the context replaces it on each transition. A memento holds a value of the state, not its behaviour. See State pattern.
Snapshots and event sourcing. An event store keeps each change as an event. A snapshot is a memento of the state after some event, so that a restore does not need to replay every event from the start.7
Persistent data structures. An immutable structure that shares the unchanged parts between versions, as the tuple of lines does above, makes each version a memento at low cost. Each version is a value, and the history is a list of values.6
Known uses
- Redux: the undo history keeps past, present and future states in the store, and undo and redo move states between them.6
- Browsers:
history.pushStateadds an entry to the session history with a serialization of the page's state.10 - Event sourcing: a snapshot of the state lets a system restore a past state and then replay the later events.7
References
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 5, Memento (Intent, Also Known As, Motivation, Applicability, Participants, Consequences, Implementation, Related Patterns)
- The Python Standard Library, copy, Python 3.14, copy.deepcopy, the difference between shallow and deep copying
- The Python Standard Library, dataclasses, Python 3.14, Frozen instances
- The Python Standard Library, dataclasses, Python 3.14, dataclasses.replace
- The Python Standard Library, pickle, Python 3.14, the warning at the top of the page
- Redux documentation, Implementing Undo History, Understanding Undo History; Designing the State Shape; Handling Undo
- Martin Fowler, Event Sourcing, Reversing Events
- The Java Language Specification, Java SE 25 Edition, 6.6.1 Determining Accessibility
- The Rust Reference, Visibility and privacy, rule vis.access
- HTML Living Standard, WHATWG, 7.2.5 The History interface, pushState
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag MFKQP4 Edit this page History Report an error Markdown