AlgoViz

Memento pattern

medium 45 min

The Memento pattern saves the state of an object outside the object without opening it up.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:49

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

  1. 1994

    The book Design Patterns appears and lists Memento among its behavioral patterns.

  2. 2005

    PostgreSQL 8.0, released on 19 January, adds savepoints: part of a transaction can be taken back without losing the rest.

  3. 2017

    Java 9 arrives on 21 September with List.of and other collections that refuse changes, useful parts for a memento.

  4. 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.

Step 1 of 3

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.

Noor, Max and the plaster casts
MaxNoor

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.

Python
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]) # True
Run it. The history has three entries, and all three are the same list.
Edit and run it in your browser

The design that hurts

reads, writesTextEditor+ text: String+ cursor: int+ fontSize: int+ write(text)History- texts: List- cursors: List- fontSizes: List+ undo()

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 knowledge of what belongs to the state should live where the state lives.

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

Originator- state+ save(): Memento+ restore(m: Memento)

1/4The originator

It holds the state and two methods. save returns a memento, restore takes one.

has (lives on)implementsdepends on

The caretaker also calls the originator, or a client calls both. That arrow is left out: both arrangements are common.

Save, change, undo

The history never sends a message to the snapshot.

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 fieldExampleIn the memento?Why
State that the user madetext, cursor, font sizeYesThis is what undo means
Computed from other stateword count, layoutNo, compute it againCosts memory and may disagree
Open resourcesfile handle, socket, lockNeverAn old handle may be closed. Keep the path instead
Links to collaboratorslisteners, logger, parent windowNoRestoring must not bring back old subscribers
Secretspassword in a formOnly with a reasonThe history keeps it longer than the form does
Passing thingsselection, animation frameUsually noReset them in restore
Identitydocument idKeep it unchangedThe restored object is still the same document
A cursor is a borderline case. Users expect it to return with the text, so editors save it.

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

The list was copied, the circle was not. Change its radius, and the memento has changed too.

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

After the last step HelloWorld can not be reached any more. Some editors keep it as a branch: an undo tree.

The stacks, step by step

ActionText after itUndo stack (top right)Redo stack (top right)
start(empty)
type HelloHello(empty)
type WorldHello World(empty), Hello
undoHello(empty)Hello World
undo(empty)Hello World, Hello
redoHello(empty)Hello World
type AgainHello Again(empty), Hello
The stacks never contain the present. Undo stack + present + redo stack together are the whole timeline.
Python
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 unreachable
Run the popular version. One undo takes back two things, and the second part of the text can never be redone.
Edit and run it in your browser

Beyond undo

Where else it helps

UseOriginatorMementoCaretaker
Text editorDocumentText and cursorUndo history
GameHero and levelSave fileSave slots, checkpoints
Drawing programCanvasLayers, or one changed tileHistory panel
SpreadsheetSheetChanged cellsUndo list
Form with a cancel buttonForm modelValues on openingThe dialog
Database transactionData pagesUndo log, old versionsTransaction manager
BrowserPageScroll place and state objectBack and forward list
Search over many triesBoard of a puzzleBoard before the moveBacktracking loop
The caretaker can also be one local variable: take a memento, try something, restore it if it failed.

Full copy, difference or inverse?

Command stores what was done. Memento stores how it was. Large editors use both.

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.

Sources