Capture and externalize an object’s internal state so that the object can be restored to this state later
Without violating encapsulation
Sometimes, it is necessary to save the state of an object and then restore it later
However, objects often encapsulate their state, making it inaccessible to other objects
A snapshot of (some portion of) an object’s state must be saved so that it can be restored to that state later, and
A direct interface to obtaining the state (i.e. accessing private fields) would expose implementation details and break encapsulation
Memento
Stores internal state of the Originator object.
Protects against access by objects other than the originator.
Originator
Creates a memento containing a snapshot of its current internal state.
Uses the memento to restore its internal state.
Caretaker
Is responsible for the memento’s safekeeping.
Never operates on or examines the contents of a memento.
Mementos are passive. Only the originator that created a memento will assign or retrieve its state.
Preserves encapsulation boundaries
Simplifies Originator
Mementos might be expensive
Defining narrow and wide interfaces for the Memento may be difficult in some languages
Hidden costs in caring for mementos (number of mementos is unknown)
Use C++ friends to implement narrow/wide interfaces for Memento
Store incremental changes instead of snapshots