ConceptDifficulty: Intermediate1 min

Memento Pattern Structure: The Class and Sequence Diagrams

Originator makes a Memento, Caretaker keeps it without opening it, and gives it back to restore.

Memento has three participants: the originator, whose state is saved; the memento, which holds the saved state; and the caretaker, which keeps mementos. This card reads their roles off the Gang of Four's class diagram, says who may read what, then follows a save, a change and a restore in a sequence diagram.

Memento participants
Each participant, its role, and what it may read
ParticipantRoleMay read the saved state
OriginatorThe object whose state is saved. Creates a memento of its current state, and restores itself from one.Yes
MementoHolds a copy of the originator's state, and offers nothing else.Holds it
CaretakerDecides when to save and when to restore, and keeps the mementos in order.No

The Gang of Four describe the memento as having two interfaces: a wide one for the originator, which can read the state, and a narrow one for the caretaker, which can only hold and pass the memento along. Every implementation of the pattern is a way of giving the caretaker that narrow interface.

The sequence diagram follows one undo. The caretaker asks for a memento before the change, keeps it, and hands it back when the user asks to undo.

Save, change and restore

The caretaker's job is the history: how many mementos to keep, which to drop, and which one undo returns. The originator's job is what goes into a memento. Neither needs to know how the other does its part.