behavioral
Memento
Capture and externalize an object's state so it can be restored to a previous point in time.
Problem
An object's internal state must be saved and restored later without exposing its implementation details.
Integration notes
Memento is useful for undo/redo, checkpoints, draft recovery, and any workflow where state history matters.
Tradeoffs
- Snapshots can consume memory if many states are stored.
- Care must be taken to keep mementos immutable and hidden from outside code.
Languages
typescript, java, python, angular, react, react-native, csharp, dotnet
Platforms
Web, Backend, Mobile, UI kits, Cross-platform systems
Variants
Scenarios
Text editor memento
A text editor stores snapshots of its content so the user can undo changes.
Language examples
Core languages
Frameworks and libraries
Text editor mementotypescript
The text editor memento stores snapshots of content so the editor can restore earlier versions without exposing its internal state.
TypeScript
class TextEditorMemento {
constructor(public readonly content: string) {}
}
class TextEditor {
private content = "";
type(text: string): void {
this.content += text;
}
save(): TextEditorMemento {
return new TextEditorMemento(this.content);
}
restore(memento: TextEditorMemento): void {
this.content = memento.content;
}
getContent(): string {
return this.content;
}
}
class History {
private snapshots: TextEditorMemento[] = [];
save(memento: TextEditorMemento): void {
this.snapshots.push(memento);
}
undo(): TextEditorMemento | null {
return this.snapshots.pop() ?? null;
}
}
const editor = new TextEditor();
const history = new History();
editor.type("Hello");
history.save(editor.save());
editor.type(" World");
history.save(editor.save());
editor.type("!");
console.log(editor.getContent());
const previous = history.undo();
if (previous) {
editor.restore(previous);
}
console.log(editor.getContent());Real-world examples
- Undo in editors: Text and graphic editors often keep snapshots so the user can revert changes.
- Save games: Games store checkpoints to restore progress after a failure or later session.
- Draft recovery: Forms and editors save drafts so users can come back without losing work.