Memento is useful when an object’s state must be captured and restored without exposing its internals broadly.
Capture and externalize an object’s internal state so the object can be restored later without violating encapsulation.
What the pattern is trying to do
Capture and externalize an object’s internal state so the object can be restored later without violating encapsulation.
What force creates the need
The system needs rollback, restore, or historical snapshots, but exposing full internal state publicly would weaken encapsulation.
How the pattern responds
Create a memento object that stores snapshot state while the originator controls what gets saved and restored.
How the moving parts fit together
An originator creates and restores mementos, while a caretaker holds them without depending on the originator’s internal details.
Java example in the Order Management domain
package org.javaomnibus.ecommerce.gof.behavioral;
public final class DraftOrder {
private String shippingAddress;
public DraftOrder(String shippingAddress) {
this.shippingAddress = shippingAddress;
}
public OrderMemento save() {
return new OrderMemento(shippingAddress);
}
public void restore(OrderMemento memento) {
this.shippingAddress = memento.shippingAddress();
}
}
public record OrderMemento(String shippingAddress) {}
Step by step
- DraftOrder controls what state enters the snapshot.
- A caller can keep snapshots without manipulating internal fields directly.
- That preserves a cleaner boundary around object state.
- Memento earns its place when restore semantics matter, not when simple reassignment would do.
Where this pattern helps
- When undo, restore, or checkpoint behavior matters
- When you need snapshots without exposing internal structure broadly
When a simpler design is better
- When state is simple and explicit reassignment is enough
- When snapshots are too large or too frequent for the performance budget
What this pattern costs
- Snapshot storage can be expensive
- Complex mutable graphs make correct restore semantics harder
How this fits today
Memento is less common than Strategy or Observer, but it remains useful in editors, workflows, drafts, recovery features, and stateful domain tools.
Where teams get it wrong
Capturing oversized object graphs as mementos without clear restore requirements can create memory cost without real product value.