Memento
Captures and externalizes an object's internal state without violating encapsulation, allowing the object to be restored to that state later.
errorWhat Problem Does the Memento Pattern Solve?
Implementing undo functionality or saving checkpoints requires storing an object's internal state externally. Exposing the object's fields to a caretaker violates encapsulation and couples the caretaker to the originator's internal implementation, making future refactoring fragile.
check_circleHow the Memento Pattern Works
Have the Originator produce a Memento object containing a private snapshot of its state. The Caretaker stores mementos without inspecting their contents—it treats them as opaque tokens. To restore, the caretaker passes a memento back to the originator, which reads its own state from it, preserving encapsulation completely.
Memento Pattern Architecture
Rendering diagram...
Implementation by Language
Memento Pattern in the Real World
“Think of a video game save point. When you save, the game (originator) packages your character's stats, inventory, and position into a save file (memento). The save system (caretaker) stores these files without understanding their contents. When you die and reload, the save file is handed back to the game, which restores everything exactly as it was.”
Frequently Asked Questions
helpHow does Memento differ from simply serializing the object?
Serialization (JSON.stringify) exposes the object's internal structure, breaking encapsulation. Memento stores state in an opaque object that only the originator can read. This prevents other code from depending on or modifying internal state directly. In practice, serialization is often acceptable for simple cases.
helpHow do I manage memory when storing many Mementos?
Limit the number of stored mementos (e.g., keep the last 50 undo states). Use incremental mementos that store only what changed (deltas) rather than full snapshots. For large objects, consider compressing memento data or persisting older mementos to disk.