Memento
Intent
Without violating encapsulation, capture and externalize an object's
internal state so that the object can be returned to this state later.
Problem
Need to restore an object back to its previous state (e.g. "undo"
or "rollback" operations).
Discussion
The client requests a Memento from the source object when it needs to
checkpoint the source object's state. The source object initializes
the Memento with a characterization of its state. The client is the
"care-taker" of the Memento, but only the source object can store and
retrieve information from the Memento (the Memento is "opaque" to the
client and all other objects). If the client subsequently needs to
"rollback" the source object's state, it hands the Memento back to the
source object for reinstatement.
An unlimited "undo" and "redo" capability can be readily implemented
with a stack of Command objects and a stack of Memento objects.
Structure
Example
The Memento captures and externalizes an object's internal state so
that the object can later be restored to that state. This pattern is
common among do-it-yourself mechanics repairing drum brakes on their
cars. The drums are removed from both sides, exposing both the right
and left brakes. Only one side is disassembled and the other serves as
a Memento of how the brake parts fit together. Only after the job has
been completed on one side is the other side disassembled. When the
second side is disassembled, the first side acts as the Memento.
[Michael Duell, "Non-software examples of software design
patterns", Object Magazine, Jul 97, p54]
Non-software example
Rules of thumb
Command and Memento act as magic tokens to be passed around and invoked
at a later time. In Command, the token represents a request; in
Memento, it represents the internal state of an object at a particular
time. Polymorphism is important to Command, but not to Memento because
its interface is so narrow that a memento can only be passed as a
value. [GOF, p346]
Command can use Memento to maintain the state required for an undo
operation. [GOF, 242]
Memento is often used in conjunction with Iterator. An Iterator can use
a Memento to capture the state of an iteration. The Iterator stores the
Memento internally. [GOF, p271]
C++ Demos | Lab