Memento
Capture and restore an object's state without breaking encapsulation.
Use it when
You need snapshots for undo or rollback.
/**
* Memento: save a game at a checkpoint and roll back after a bad fight.
*
* Real-world scenario: a game with checkpoints. The game takes a snapshot of the
* player's state (level, health, inventory) and hands it to a save system. The
* save system stores snapshots but never looks inside them; only the game knows
* how to restore one. So the game's internals stay private, and rollback is easy.
*/
// Memento: a frozen snapshot. readonly + Object.freeze, so nothing in it can change.
interface Snapshot {
readonly level: number;
readonly health: number;
readonly inventory: readonly string[];
}
// Originator: owns the state, creates snapshots and restores from them.
class Game {
private level = 1;
private health = 100;
private inventory: string[] = [];
play(move: { level: number; healthChange: number; found?: string }): void {
this.level = move.level;
this.health += move.healthChange;
if (move.found) {
this.inventory.push(move.found);
}
}
save(): Snapshot {
return Object.freeze({
level: this.level,
health: this.health,
inventory: Object.freeze([...this.inventory]),
});
}
restore(snapshot: Snapshot): void {
this.level = snapshot.level;
this.health = snapshot.health;
this.inventory = [...snapshot.inventory];
}
toString(): string {
return `level ${this.level}, health ${this.health}, items ${JSON.stringify(this.inventory)}`;
}
}
// Caretaker: keeps snapshots safe but never reads or changes them.
class Checkpoints {
private readonly saves: Snapshot[] = [];
push(snapshot: Snapshot): void {
this.saves.push(snapshot);
}
last(): Snapshot {
return this.saves[this.saves.length - 1];
}
}
function clientCode(): void {
const game = new Game();
const checkpoints = new Checkpoints();
game.play({ level: 2, healthChange: -20, found: "sword" });
checkpoints.push(game.save());
console.log(`Checkpoint saved: ${game}`);
game.play({ level: 3, healthChange: -75, found: "cursed ring" });
console.log(`After boss fight: ${game}`);
game.restore(checkpoints.last());
console.log(`Back to checkpoint: ${game}`);
}
clientCode();
// Output:
// Checkpoint saved: level 2, health 80, items ["sword"]
// After boss fight: level 3, health 5, items ["sword","cursed ring"]
// Back to checkpoint: level 2, health 80, items ["sword"]How it works
| Role | Classes | What it does |
|---|---|---|
| Memento | Snapshot | A frozen, readonly copy of the game's state at one moment |
| Originator | Game | Owns the state; save() creates a snapshot and restore() rolls back to one |
| Caretaker | Checkpoints | Stores snapshots but never reads or changes them |
| Client | clientCode() | Saves at a checkpoint, plays on, then restores |