Memento: preserve a restorable snapshot
Picture
Save a document snapshot before editing. A history manager can hold it without implementing how restoration works.
Predict
Does restoring local state reverse every external side effect?
Walk through the small example
No. External actions need their own compensation or recovery rules.
Mental model and complete Python solution
Memento stores an originator’s state while a caretaker holds the snapshot. The frozen snapshot includes an identity token so another document cannot use it accidentally. Command packages an action; memento packages a restorable state. Editors often combine them, while limiting history or sharing immutable structure to control storage.
What the function promises: Snapshots are local to one Document instance and restore its text. No distributed rollback or concurrent edit merging is provided.
from dataclasses import dataclass
@dataclass(frozen=True)
class Memento:
owner: object
text: str
class Document:
def __init__(self, text=""):
self.text, self._identity = text, object()
def snapshot(self):
return Memento(self._identity, self.text)
def restore(self, snapshot):
if snapshot.owner is not self._identity:
raise ValueError("Wrong document")
self.text = snapshot.text
doc = Document("before")
saved = doc.snapshot()
doc.text = "after"
doc.restore(saved)
assert doc.text == "before"
Work and storage: Retained snapshots keep old state alive. Immutable strings may share storage; mutable graphs may require copying.
When to recognize it: A restored document does not undo an email already sent. Snapshot history also consumes storage that needs a lifetime policy.
Check before applying it: Snapshot scope, compatibility, and history lifetime must be explicit.
Change one rule
A document is very large and changes by tiny edits. Must every snapshot copy everything?
See what changes
Not necessarily. Persistent data structures, structural sharing, or edit logs can reduce storage, but need their own ownership and reconstruction rules.
Connect
Command: make an action a value: Commands can save a memento to support their undo operation.
Make failure and retries part of the design: Restoration needs tests for ownership, stale state, and conflicting edits.