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(); }
}