Memento Pattern

The Memento pattern: saving an object's state as a snapshot only that object can read, so it can be restored later, and keeping the snapshots from filling the memory.

  • 8 cards
  • 4 questions
  • About 16 min
  • Intermediate to Advanced
Share

Undo needs a copy of an object's state from before the change. If the code that keeps the copies reads the object's fields directly, those fields must be public, and every caller can now change them too. The Memento pattern lets the object make the copy itself, as a snapshot that only it can read, and hand it to another object that keeps it and gives it back to restore.

This topic opens on state made public for the sake of undo, then reads the three participants off the class diagram and follows a save and a restore in a sequence diagram. The template shows how far each language can hide a snapshot's contents: a Java nested class, a TypeScript private field, and Python's leading underscore.

Two examples follow: undo in a drawing canvas, and save points in a game, where the save menu lists many snapshots without opening any. The gotcha is snapshots that fill the memory, with measured figures for three ways of keeping them, and the exercise names the participants in a form with undo.

By the end you can recognise a memento, write one, name each participant in a design, and choose how many snapshots to keep.

Contents

8 cardsnot started