Design Patterns

Memento



Design Pattern Type: Behavioral

GoF Statement of Intent:


Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
Brief Overview:



Provides the ability to restore an object to its previous state, i.e. an undo. The Momento pattern uses two objects; the "originator" and a "caretaker". The originator is some object that has an internal state. The caretaker is going to ask the originator to do something but wants to be able to undo the change if necessary. so it first asks for a memento object. After performing the change if it is necessary to "undo" the change the caretaker passes the momento object back to the originator to return it to the previous state.
UML Diagram:

Discussion and In-class Example:

Many video games provide the ability to back up a step if necessary, like when you have a high level character make a really dumb move and get snuffed? The game designers have a "back up mode" that allows you to resurrect your character in the state it was just prior to being snuffed. This is the Memento at work.
The Memento has two goals
  1. Saving the important state of a system’s key object.
  2. Maintaining the key object’s encapsulation.

Following the design principle of having a class have a single responsibility it is best to keep the state as a separate object from the object whose state is being preserved.