Cheatsheet
Memento
Intent
Save an object's state in an opaque snapshot so you can go back to it later, without whoever keeps it having to know or touch the inner details.
Structure (UML)
classDiagram
direction LR
class WhiteboardDraft {
<<Originator>>
+snapshot() Snapshot
+restore(Snapshot s)
+edit(title, movements, cap)
+clear()
}
class Snapshot {
<<Memento>>
}
class DraftHistory {
<<Caretaker>>
+save(Snapshot snapshot)
+undo() Snapshot
}
WhiteboardDraft ..> Snapshot : creates
DraftHistory o-- SnapshotParticipants
- Originator (WhiteboardDraft), creates the snapshot and knows how to restore itself from it
- Memento (WhiteboardDraft.Snapshot), the frozen copy; only the originator reads what's inside
- Caretaker (DraftHistory), keeps snapshots and hands them back without looking inside
WhiteboardDraft.java
/** The memento: a frozen copy of the draft. Only WhiteboardDraft can read what's inside. */
public static final class Snapshot {
private final String title;
private final List<String> movements;
private final int timeCapMinutes;
private Snapshot(String title, List<String> movements, int timeCapMinutes) {
this.title = title;
this.movements = List.copyOf(movements);
this.timeCapMinutes = timeCapMinutes;
}
}
public Snapshot snapshot() {
return new Snapshot(title, movements, timeCapMinutes); // every field, without exposing any
}
public void restore(Snapshot s) {
title = s.title;
movements.clear();
movements.addAll(s.movements);
timeCapMinutes = s.timeCapMinutes;
}Pros
- The draft keeps its fields private; nobody else needs getters or setters
- A new field goes into the snapshot in one place, without touching the history
- Undo any change, even those with no inverse operation (wiping the board)
Cons
- Every snapshot is a copy; with big states or many steps, it costs memory
- You have to bound the history and decide when to save
- If the object points to other mutable objects, the copy has to be deep or share only immutable things