Memento pattern
medium 45 minThe Memento pattern saves the state of an object outside the object without opening it up.
Video lesson · Chapter 1 of 6
Make a prediction
Memento
1:02Reel
Theory
Read or listen first. About 2 min.
What it is
Memento is a behavioral design pattern. An object, the originator, puts its state into a second object, the memento. A third object, the caretaker, keeps it and gives it back when the state is wanted again.
The special part is the privacy. The caretaker holds the memento but can not use what is in it. To the caretaker it is a closed token, to the originator an open book.
So undo, rollback and saving can be written without making a single field public.
Why it exists
Going back needs the old state, and the old state is private. Copying it from outside means that other classes must know all fields. They break whenever a field is added, and they can put the object into a state it would never enter by itself.
With Memento the class that owns the fields also decides which of them count. The history needs no change when they do.
It separates two questions that change for different reasons. How to save is the originator's business. When to save, how many to keep, and which to return to is the caretaker's.
It also works where an inverse does not exist: blurring a picture, deleting text, moving a random number generator on.
A short history
1994
The book Design Patterns appears and lists Memento among its behavioral patterns.
2005
PostgreSQL 8.0, released on 19 January, adds savepoints: part of a transaction can be taken back without losing the rest.
2017
Java 9 arrives on 21 September with
List.ofand other collections that refuse changes, useful parts for a memento.Today
The help of Vim describes undo branches: text that was undone before a new change can still be reached. It calls the result an undo tree.
Words to know
- Originator
- The object whose state is saved. It creates and reads mementos.
- Memento
- A fixed copy of a state, closed to everyone but the originator.
- Caretaker
- Keeps mementos, decides when to save and restore, never looks inside.
- Narrow interface
- What the caretaker sees of a memento: at most a label.
- Wide interface
- What the originator sees: all saved values.
- Snapshot
- A copy of the whole state at one moment.
- Difference (delta)
- Only what changed between two states.
- Shallow copy
- A copy that shares its parts with the original.
- Deep copy
- A copy that shares nothing that can change.
- Coalescing
- Joining several small changes into one undo step.
- Undo tree
- A history that keeps the branches a linear history would drop.
- Savepoint
- A mark inside a transaction to which one can roll back.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Save. The originator makes a closed copy
Understand it
Start here
Keep it without looking inside
You are about to change something, and you may want it back. So you keep a copy of how it was. The question is who makes the copy, who keeps it, and who may look inside. The Memento pattern gives these three jobs to three different objects.
Max could run this shelf for jelly or for snowmen. Max does not know what a tower is.
Three participants
Originator
Owns the state. Makes a memento of it and returns to one. Examples: a text editor, a game character, a form, a random number generator.
Memento
One saved state. Nobody changes it. Examples: an editor snapshot, a game save, a savepoint, a backup of a configuration.
Caretaker
Keeps mementos and hands them back. Decides when. Never looks inside. Examples: an undo history, a save slot manager.
Why
What goes wrong without it
The first idea is usually that the history reads the fields it needs. Then it must know every field, and so must every other class that wants to save. The second idea is to keep a reference. That is not a copy at all.
class Drawing: def __init__(self): self.shapes = []history = []d = Drawing()history.append(d.shapes) # "save"d.shapes.append("circle")history.append(d.shapes) # "save"d.shapes.append("square")history.append(d.shapes) # "save"d.shapes = history[0] # "undo" to the empty drawingprint(d.shapes) # ['circle', 'square']print(history[0] is history[2]) # TrueThe design that hurts
1/3The fields become public
Undo needs the state, so somebody made the fields public. Now anyone can set a cursor that points behind the end of the text.
uses
The object makes its own memento
- Fields stay private
- One class knows what belongs to the state
- A memento can not be changed
- Restoring is one method that can check everything
Others copy the fields
- Fields must be readable and writable
- Every saver repeats the list of fields
- A saved state is easy to change by accident
- A restore can leave an impossible mixture
The idea
Two faces of one object
A memento shows one face to everybody and another one to its originator. The caretaker sees a narrow interface: it can hold the thing, perhaps show a label. The originator sees the wide interface: all the saved values.
The Memento pattern in general
1/4The originator
It holds the state and two methods. save returns a memento, restore takes one.
has (lives on)implementsdepends on
Save, change, undo
What to keep
Which fields belong in it?
The originator decides. Not everything it holds is worth saving, and some things must not be saved.
| Kind of field | Example | In the memento? | Why |
|---|---|---|---|
| State that the user made | text, cursor, font size | Yes | This is what undo means |
| Computed from other state | word count, layout | No, compute it again | Costs memory and may disagree |
| Open resources | file handle, socket, lock | Never | An old handle may be closed. Keep the path instead |
| Links to collaborators | listeners, logger, parent window | No | Restoring must not bring back old subscribers |
| Secrets | password in a form | Only with a reason | The history keeps it longer than the form does |
| Passing things | selection, animation frame | Usually no | Reset them in restore |
| Identity | document id | Keep it unchanged | The restored object is still the same document |
The state contains a list of shapes, and shapes can be changed. How do you save it?
BreaksKeep the reference
- How
Snapshot(self.shapes).- Limit
- The history changes whenever the drawing does.
- Choose when
- Never, unless the list can not change.
WorksCopy everything deeply
- How
copy.deepcopy(self.shapes), or a copy per class.- Limit
- Time and memory per save. Copies things you wanted to share, such as images, and can follow a link to the whole program.
- Choose when
- Small states, or few saves.
StrongMake the parts unchangeable
- How
- Shapes are frozen, the list is a tuple. Saving copies one list of references. Moving a shape creates a new shape.
- Limit
- The editing code must be written that way. See immutability.
- Choose when
- When you save often.
What a shallow copy shares
Undo and redo
Two stacks
Undo is the most frequent use. Save the state before each change. Undo puts the present on the redo stack and returns to the top of the undo stack. Redo does the same in the other direction. A new change throws the redo stack away.
One timeline, and a fork
The stacks, step by step
| Action | Text after it | Undo stack (top right) | Redo stack (top right) |
|---|---|---|---|
| start | (empty) | ||
| type Hello | Hello | (empty) | |
| type World | Hello World | (empty), Hello | |
| undo | Hello | (empty) | Hello World |
| undo | (empty) | Hello World, Hello | |
| redo | Hello | (empty) | Hello World |
| type Again | Hello Again | (empty), Hello |
class AfterHistory: def __init__(self): self.undo_stack, self.redo_stack = [], [] def save(self, text): self.undo_stack.append(text) self.redo_stack.clear() def undo(self): if not self.undo_stack: return None self.redo_stack.append(self.undo_stack.pop()) return self.undo_stack[-1] if self.undo_stack else Noneh = AfterHistory()text = "Hello"h.save(text)text += " World"h.save(text)text += " and friends" # typed, not saved yettext = h.undo()print(text) # Hello: one undo, two changes goneprint(h.undo()) # None: the empty page is unreachableBeyond undo
Where else it helps
| Use | Originator | Memento | Caretaker |
|---|---|---|---|
| Text editor | Document | Text and cursor | Undo history |
| Game | Hero and level | Save file | Save slots, checkpoints |
| Drawing program | Canvas | Layers, or one changed tile | History panel |
| Spreadsheet | Sheet | Changed cells | Undo list |
| Form with a cancel button | Form model | Values on opening | The dialog |
| Database transaction | Data pages | Undo log, old versions | Transaction manager |
| Browser | Page | Scroll place and state object | Back and forward list |
| Search over many tries | Board of a puzzle | Board before the move | Backtracking loop |
Full copy, difference or inverse?
Use it when
- You must return to an earlier state
- The state should stay private
- An inverse of the change is hard or impossible
- You want to try something and take it back
Leave it when
- The change has an easy inverse: plus 1, minus 1
- The state is huge and changes everywhere
- Effects leave the object: mails, payments, files
- The object is immutable: keep the old object itself
The price
Memory
Each memento costs. 1,000 copies of a 1 MB document are 1 GB.
Time
A deep copy on every key press makes typing slow.
Forgotten fields
A new field that nobody adds to the memento is not restored. A test must catch it.
The world does not go back
Restoring an order does not take back the email that was sent.
Summary
The whole topic in one minute.
The originator makes a closed copy of its state, the caretaker keeps it, and only the originator opens it again. The copy must be its own, fixed and complete.
Undo: save before each change, save the present before going back, restore before moving entries, and clear redo on a new change. The present is on no stack.
In production: a budget in bytes, joined steps, differences or shared structure, one immutable state against torn reads, and on disk a version, a checksum and a rename. Effects outside the object do not come back.
- The originator saves and restores itself. The caretaker keeps. The memento stays closed.
- Own, fixed, complete: no shared mutable parts, no setters, no missing field.
- Save before the change. Undo first saves the present for redo.
- A new change clears the redo stack.
- Give the history a limit, and join small changes into one step.
- Memento keeps how it was. Command keeps what was done.