# Purpose
Captures and stores the current state of an object to be able to restore it later, without violating encapsulation.
# Problem
-
State Restoration: Need to go back without exposing internal implementation.
-
Encapsulation Violation: Prevent external objects from manipulating the private state.
# Solution
Delegate the creation of a state copy (Memento) to the object itself (Originator). A Caretaker manages the history without seeing the details.
# Structure
# Participants
- Memento: The state snapshot.
- Originator: Creates the memento and restores its state from it.
- Caretaker: Maintains the memento stack (history).
# When to Use It
To implement "undo/redo" functionality or naturally keep state histories without exposing the origin class.
# Advantages
-
verified
Encapsulation: The state remains private.
-
verified
Simplification: Originator doesn't manage its own history.
# Disadvantages
-
warning
Memory: Many snapshots consume significant resources.
-
warning
Incompatibility: Old mementos can fail if the class changes.
# Example: Text Editor (Undo)
Store editor content before each change in a stack to allow rollback.
# Java Code
class Memento {
private final String state;
public Memento(String s) { state = s; }
public String getState() { return state; }
}
class Editor {
private String text;
public Memento save() { return new Memento(text); }
public void undo(Memento m) { text = m.getState(); }
}
# Mapping Participants
- TextMemento: Memento.
- TextEditor: Originator.
- Caretaker: Change stack manager.
# Conclusions
Robust solution to implement state rollback in a clean and maintainable way.
# Related Patterns
Command
To implement complete reversible actions.
Iterator
To navigate the memento history.