Memento
Overview
Capture and externalize an object's internal state so it can be restored later.
When to use
- You need undo/redo.
- You want to keep state history without exposing internals.
Java example
class Editor {
private String content = "";
void type(String text) {
content += text;
}
Snapshot save() {
return new Snapshot(content);
}
void restore(Snapshot snapshot) {
content = snapshot.content;
}
static final class Snapshot {
private final String content;
private Snapshot(String content) {
this.content = content;
}
}
}
TypeScript example
class Snapshot {
constructor(readonly content: string) {}
}
class Editor {
private content = '';
type(text: string): void {
this.content += text;
}
save(): Snapshot {
return new Snapshot(this.content);
}
restore(snapshot: Snapshot): void {
this.content = snapshot.content;
}
}
In languages without nested access control, keep the memento type module-private if you want stronger encapsulation.
Pros and cons
Pros:
- Enables undo/redo without exposing internals.
- Clear separation of state snapshots.
Cons:
- Memory usage can grow quickly.
- Snapshot creation may be expensive.
Common pitfalls
- Saving too frequently without limits.
- Storing large, deep object graphs.