AlgoViz

Memento pattern

medium 45 min

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

Watch lesson4:49

Where it shows up

The same pattern appears across everyday software.

  • Python random

    `random.getstate()` returns an object that captures the internal state of the generator, and `setstate()` restores it. You keep it, the generator reads it: a memento in two functions.

  • Java Swing undo

    `StateEdit` asks an object that implements `StateEditable` to store its state before and after an edit, and uses them for undo and redo. The undo manager is the caretaker.

  • PostgreSQL savepoints

    `SAVEPOINT` sets a mark inside a transaction. `ROLLBACK TO SAVEPOINT` takes back everything after it and restores the state of that moment, while the transaction goes on.

  • Git

    The Git book explains that Git thinks of its data as a series of snapshots of a small filesystem, not as a list of differences. A commit is a memento with a name and a parent.

  • Redux undo

    The Redux documentation builds undo with past, present and future. Because state is never changed in place, keeping an old state means keeping a reference.

  • Immer patches

    Immer records patches and inverse patches for a change. Its documentation shows them used to take changes back: differences instead of full copies.

  • Browser history

    `history.pushState` stores a state object with an entry. When the user returns, the `popstate` event carries a copy of it. The browser is the caretaker.

  • Android saved state

    Screens put small values into saved instance state so that they survive when the system ends the process. The guide says what belongs there and that space is limited.

  • ProseMirror history

    The history plugin keeps 100 events by default and starts a new group after a pause of 500 milliseconds or when changes are not adjacent: a limit and coalescing.

  • .NET IEditableObject

    `BeginEdit`, `CancelEdit` and `EndEdit` let a row keep a backup of its own values while it is being edited, and return to it on cancel.