This technique is used to capture an object's present state and store it in a way that allows it to be restored later without violating the encapsulation restrictions.
Examples of Memento Patterns
Examples of memento patterns include:
Undo Operation
Transaction Rollback
Memento Pattern with UML diagram
The classes, interfaces, and objects in the above UML class diagram are defined as follows.
Originator: This class generates a memento object providing a snapshot of the originator's current state. It also resets the Originator to a previously saved state using the SetMemento procedure.
Memento: This class contains information about the originator's preserved state.
Caretaker: This class is used to store Memento objects for later use. This merely serves as a storage; it never examines or modifies the contents of the Memento object.
When Should You Use the Memento Design Pattern?
The memento design pattern is important in the following scenarios:
An object's state must be saved and restored later.
It cannot be accessible directly through an interface without revealing implementation.
Advantages of the Memento Design Pattern
Undo Mechanism: Provides an undo mechanism by storing the object's previous state.
Preserving Encapsulation: Because only the originator can store and retrieve information from the memento, the encapsulation is not violated.
Ease of Restoration: The originator can return the state to an earlier point in time.