Memento Pattern

Synopsis

The memento pattern is used to encapsulate the current state of an object in a memento object in order to be able to restore the object state later without exposing the internal representation of the object to the outside world.

Context

Suppose you have a an object which stores form information and you would like to allow the user to make changes in the form and then if they make a mistake later you can put back in the original form values. Well, you could serialize the form object and then unserialize it later but this is obviously messy and not a good solution. Another possible solution would be to have an outside object use the form's accessor methods to pull out what you need to save the state but this causes high coupling between the class saving the state and the form; any changes in the form would require changes in the other class. We need something that will allow you to save the state and restore it later without having to get involved in the details. This is where the memento pattern comes in.

Forces

The memento pattern is useful when you have an object which you would to take a "snapshot" of so that at a later time you could use the snapshot to restore it to its original state, such as an undo or rollback operation. But at the same time, you do not want to have to know about the details of how this occurs or the how the state is internally represented.

Solution

The solution to this problem is make use of a Memento object which is responsible for storing the snapshot or current state. When a Memento object is needed, the Caretaker object, the object responsible for storing the Memento object, requests a Memento from the Originator via the createMemento() method. The state can then later be restored by passing the a Memento to the Originator.setMemento() method.

This diagram is from javacoder.net

(NOTE: There is an error in the UML diagram. Originator.createMomento() should return a Memento object rather than void.)

Consequences

Care should be taken that a Memento object relates only to its Originator and does not change multiple objects as this could increase coupling and cause problems later.

Implementation

See the example eclipse project in the mementopattern.zip file.

Related Patterns

Command

Author: Dan Adams <danno@wpi.edu>