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

See it run

Who makes the copy, who keeps it, and what happens on undo.

Operations

TextCraft session

Type twice, undo twice, redo, type again. The history never looks into a memento.

Step 1 of 10

TextCraft opens

writerWritereditorTextEditortextcursor0historyHistoryundononeredonone

Text: empty

An empty text. No mementos.

Step 1: TextCraft opens

class History:    def checkpoint(self):        self._undo.append(self._editor.save())        self._redo.clear()    def _move(self, source, target):        if not source:            return False        now = self._editor.save()        self._editor.restore(source[-1])        source.pop()        target.append(now)        return True
Watch
The mementos on the right
Result
Every state comes back

The present is never on a stack.

In the real world

The same memento pattern doing real jobs. Pick one and step through it.

Autosave reads two fields while somebody types.

Step 1 of 3

Read the text

autosaveThread 1typingThread 2editorTextEditortextHellocursor5mementoSnapshottextHellocursor?textHello

Autosave has Hello.

Step 1: Read the text

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Keeping a reference

    critical

    The past changes with the present.

    Wrong
    history.append(self.shapes)
    Right
    history.append(tuple(self.shapes))
  • Saving after the change

    critical

    The first state is never saved, and unsaved work is lost on undo.

    Wrong
    editor.write(text)history.checkpoint()
    Right
    history.checkpoint()editor.write(text)
  • Popping before restoring

    major

    If restore raises, the step is gone.

    Wrong
    m = self._undo.pop()self._editor.restore(m)
    Right
    self._editor.restore(self._undo[-1])self._undo.pop()
  • Public getters on the memento

    major

    Everyone can read the private state, and soon someone does.

    Wrong
    history.last().get_text()
    Right
    history.last().describe()
  • Frozen outside, soft inside

    critical

    A frozen field can hold a list that changes.

    Wrong
    @dataclass(frozen=True)class Save:    bag: list
    Right
    @dataclass(frozen=True)class Save:    bag: tuple
  • No limit

    major

    A long session fills the memory.

    Wrong
    self._undo.append(m)
    Right
    self._undo.append(m)while self._bytes > self._budget: ...

Interview tips

  • Three promises

    • Own.
    • Fixed.
    • Complete.
  • Undo in order

    • Save now.
    • Restore target.
    • Move entries.
  • Leave out

    • Open files.
    • Listeners.
    • Computed values.
  • Pay less

    • Join typing.
    • Limit bytes.
    • Keep only the part.
  • Test

    • Round trip.
    • Restore twice.
    • A failing restore.