Memento

From CSSEMediaWiki
Revision as of 03:42, 25 July 2009 by JaninaVoigt (Talk | contribs)
Jump to: navigation, search

The Memento pattern is a way to store historical records of the state (or some portion of the state) of an object. A memento can be thought of as a souvenir. Much as a Mickey Mouse soft toy might bring back memories of what Disneyland was like when you visited, a Memento object allows the object which made it to remember what state it was in when the Memento was constructed. Using this information, it can then restore that previous state.

The object whose historical state we are saving is known as the Originator class for the pattern. The goal is to avoid breaking the encapsulation of the Originator. The Memento objects for a particular Originator are stored in a Caretaker class. The Caretaker object is probably the most crucial part of the pattern, as this object allows for the key feature: It stores each Memento without knowledge of its internal details.

Thus the Originator shares (some of) its internal state with the Memento object, but not to any other class. The state information remains fully encapsulated by the Originator, except when creating a Memento. Ideally, the state information in a Memento object could only be accessed by its Originator object, and no other classes (C++ allows for this with "friend" classes, but Java doesn't AFAIK, not sure about C#). In any case, no classes besides the originator need or should use the Originator.

Use When

Use the Memento pattern when:

  • You need to save a snapshot of an object's state so that you can maybe restore it later, and
  • You don't want to break the encapsulation of an object by adding getters and setters so that its state can be obtained from the outside.

Structure

From the Gang of Four Design Patterns book:

MementoStructure.png


See also


Personal tools