Pattern · Core

Memento

Capture an object's internal state into an opaque snapshot you can stash away and restore later — implementing undo without breaking encapsulation.

Asked atAmazonAdobeFigma
step 1 / 8
Snapshot & restore
createskeeps*
Editor
- text
+ save(): Memento
+ restore(m)
Memento
- text
(opaque)
History
- stack
+ push(m)
+ pop()
Snapshot & restore
1class Editor {
2 String text;
3 Memento save() { return new Memento(text); }
4 void restore(Memento m){ text = m.getText(); }
5}
6class History {
7 Stack<Memento> stack;
8 void push(Memento m){ stack.push(m); }
9 Memento pop() { return stack.pop(); }
10}
State
Originatorsnapshots itself
Mementoopaque token

The Editor (Originator) can save() its state into a Memento and restore(m) from one. It alone knows how to read the snapshot it creates — to everyone else the Memento is opaque.