All PatternsBehavioral
Memento
Captures and restores an object's internal state.
Undo systemsCheckpointsState snapshots
Understanding Memento
The Memento pattern captures an object\'s internal state as a snapshot that can be restored later, without exposing the object's implementation details. This is the pattern behind undo systems, checkpoints, and state history. In Go, the originator creates a memento struct containing a copy of its state, and a caretaker stores these mementos in a stack or list. When the user requests an undo, the caretaker retrieves the previous memento and passes it back to the originator to restore its state.
Key Concepts
- •Originator — the object whose state needs to be saved and restored — creates and consumes mementos
- •Memento — an opaque snapshot of the originator\'s state — typically an unexported struct in Go
- •Caretaker — stores mementos but never examines or modifies them — just holds the history stack
- •Encapsulation preserved — memento captures state without exposing the originator\'s internal structure
When to Use
✅ Use when
- • You need undo/redo functionality for complex objects
- • You want to create checkpoints or savepoints for recovery
- • You need to capture and restore state without violating encapsulation
- • You\'re building a version history or state timeline feature
⚠️ Avoid when
- • The object\'s state is large and frequent snapshots would consume too much memory
- • A simpler approach like copying a struct is sufficient in Go
- • You only need to track one level of undo — saving the previous value is simpler
Structure
Originator (creates/restores)
↓ Save() / Restore()
Memento (state snapshot)
↓ stored by
Caretaker (history stack)
How It Works
Originator
Editor
state: "Hello"
📦 Memento
"Hello"
Caretaker
History
M
Object has state
1
Object State
Object has internal state that can change.
1 / 4
Basic Implementation
Text editor with undo history:
main.go
Loading editor...
Real-World Example: Game Save System
Game with save slots:
main.go
Loading editor...