Memento
Snapshot an object's state and store it externally so you can restore it later — without breaking encapsulation or exposing internals.
Intent & Description
🎯 Intent
Save and restore object state for undo/redo, checkpointing, or state rollback without leaking private implementation details.
📋 Context
You’re building a text editor, drawing app, game with save states, or any system where users can undo actions. The object holding the state shouldn’t expose its internals just to support snapshotting.
💡 Solution
The Originator (object being saved) creates a Memento — an opaque snapshot of its private state. A Caretaker stores and manages Mementos without being able to read them. When rollback is needed, the Originator restores from a Memento.
Real-world Use Case
Source
📌 TL;DR
Snapshot state → store externally → restore when needed. Encapsulation intact. The classic undo/redo foundation. Watch RAM usage if you snapshot large objects frequently.
Advantages
- Snapshots are stored externally without violating the object’s encapsulation.
- Originator code stays clean — the Caretaker owns the history management.
Disadvantages
- Can devour RAM fast if mementos are created frequently or if the state is large.
class Memento {
constructor(state) { this.state = state; }
getState() { return this.state; }
}
class Originator {
constructor(state) { this.state = state; }
save() { return new Memento(this.state); }
restore(memento) { this.state = memento.getState(); }
}