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
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
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
Autosave has Hello.
Step 1: Read the text
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Keeping a reference
criticalThe past changes with the present.
Wronghistory.append(self.shapes)Righthistory.append(tuple(self.shapes))Saving after the change
criticalThe first state is never saved, and unsaved work is lost on undo.
Wrongeditor.write(text)history.checkpoint()Righthistory.checkpoint()editor.write(text)Popping before restoring
majorIf restore raises, the step is gone.
Wrongm = self._undo.pop()self._editor.restore(m)Rightself._editor.restore(self._undo[-1])self._undo.pop()Public getters on the memento
majorEveryone can read the private state, and soon someone does.
Wronghistory.last().get_text()Righthistory.last().describe()Frozen outside, soft inside
criticalA frozen field can hold a list that changes.
Wrong@dataclass(frozen=True)class Save: bag: listRight@dataclass(frozen=True)class Save: bag: tupleNo limit
majorA long session fills the memory.
Wrongself._undo.append(m)Rightself._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.