What is memento?
A memento is a software design pattern that lets you capture the internal state of an object at a specific moment, store it safely, and restore that state later without exposing the object’s private details. Think of it like taking a snapshot of a program’s data so you can go back to that exact point if needed.
Let's break it down
The pattern has three main parts:
- Originator - the object whose state you want to save. It knows how to create a memento containing its current data and how to restore itself from that memento.
- Memento - a simple container that holds the saved state. It doesn’t have any behavior; it just stores data and keeps it hidden from the outside world.
- Caretaker - the manager that keeps the memento(s). It can request a new snapshot from the originator, store it, and later give it back to the originator to roll back. The caretaker never looks inside the memento, preserving encapsulation.
Why does it matter?
Being able to revert an object to a previous state is essential for features like “undo” and “redo,” error recovery, and temporary state changes. The memento pattern provides this capability while keeping the object’s internal structure private, which helps maintain clean, modular code.
Where is it used?
- Text editors and word processors (undo/redo of typing)
- Graphic design tools (reverting changes to images or drawings)
- Video games (save points, checkpoints)
- Database transactions (rolling back to a safe state after a failure)
- Any application that needs to temporarily store a configuration or user session and restore it later.
Good things about it
- Preserves encapsulation: the object’s private data stays hidden.
- Simple to implement for objects with clear state snapshots.
- Makes undo/redo logic straightforward and reusable.
- Decouples the object that creates the state from the one that stores it, allowing flexible storage strategies (in memory, on disk, etc.).
Not-so-good things
- Can consume a lot of memory if many large snapshots are kept.
- Requires careful handling of deep copies; shallow copies may lead to unexpected side effects.
- Adds extra classes and code, which can increase complexity for very simple use‑cases.
- Restoring state may not be trivial if the object holds external resources (file handles, network connections) that aren’t captured in the memento.