What It Is
The Memento pattern saves a snapshot of an object's state so it can be restored later — without showing the object's insides to anyone. The object itself makes the snapshot and itself restores from it; the outside world just holds the snapshots.
This is the pattern behind "undo to a saved point", drafts, and checkpoints.
Example: Editor Snapshots
Save() returns a snapshot; Restore() takes one back. The mistake in between simply disappears.
Save, break, restore
The snapshot was taken while the text was good. After the bad edit, Restore(saved) brings the exact old state back — the holder of the snapshot never looked inside it.
Output: Go program and captured output
package main
import "fmt"
type Editor struct {
text string
}
// The memento: a saved snapshot of the state.
type Snapshot struct {
text string
}
func (e *Editor) Save() Snapshot {
return Snapshot{text: e.text}
}
func (e *Editor) Restore(s Snapshot) {
e.text = s.text
}
func main() {
e := &Editor{}
e.text = "Hello, world!"
saved := e.Save()
e.text = "Hello, wrold! oops"
fmt.Println("now: ", e.text)
e.Restore(saved)
fmt.Println("undo:", e.text)
}
When to Use It
Use it for checkpoints and rollback: editor undo, game saves, "restore defaults", transactional steps that may need reverting.
Skip it when the state is one or two plain values — just keep the old value in a variable. And compare with Command: commands undo step by step, mementos jump back to a saved point.
Pros and Cons
Pros: real rollback without exposing internals; snapshots are simple values that can be kept in lists for multi-level undo.
Cons: snapshots of big state cost memory fast; deciding what belongs in the snapshot (and keeping it complete as the type grows) is easy to get wrong.