Definition
Think of the undo button in a text editor. When you type new text, the old text is gone unless something saved it. The Memento Pattern is a behavioral design pattern that lets an object save a copy of its state and restore it later. The object does not show its inner data to anyone.
It is used to build undo/redo. It keeps encapsulation, which means the object's data stays private.
Key Components
- Originator: The object whose state needs to be saved (e.g.,
TextEditor). It creates and reads the snapshots. - Memento: A snapshot (a saved copy) of the Originator's state (e.g.,
EditorMemento). - Caretaker: Keeps the mementos, for example in a stack. It does not open or change them.
Benefits
- Makes undo/redo simple to add.
- Keeps encapsulation: the internal state stays private.
- Makes state easier to manage in editors, games, or transactions.
Real-world Example
- Text editors (Undo/Redo).
- Version control systems.
- Graphic design tools with history tracking.