Applied Design Patterns with Java
Behavioral :: Memento (283) {C ch 21}
Implementation
The following implementation issues are relevant to the
Memento pattern:
- Language support. Mementos have two interfaces: a wide
one for originators and a narrow one for other objects. Ideally the implementation language will support two levels
of static protection. C++ lets you do this by making the Originator a friend of Memento and making Memento's wide interface private. Only the narrow interface should be declared public.
Java does not support friend;
however, the Java JDK does have a Serializable interface, which any class can implement to privately write an object's state
to a file or stream.
- Storing incremental changes. When Mementos get created and passed back to their originator in a predictable
sequence, then Memento can save just the incremental change to the originator's internal state.
For example, undoable commands in a history list can use Mementos to ensure that commands are restored to their exact state when
they're undone (Command (233). The history list defines a specific order in which commands can
be undone and redone. That means Mementos can store just the incremental change that a command makes rather
than the full state of every object they affect.
Related Patterns
Command (233): Commands can use Mementos to maintain state for undoable operations.
Iterator (257): Mementos can be used for iteration.
Catalog Behavioral Prev Next