Catalog / Behavioral Patterns / Memento Pattern
BEHAVIORAL

Memento Pattern

Capture and externalize an object’s internal state without violating encapsulation, so that the object can be restored to this state later.

Intent & Objective

Save snapshots of an object’s internal state so that it can be restored without exposing its private fields to external objects.

👥 Real-World Human Analogies & Social Roles
2 Intuitive Scenarios
RPG Game Save Checkpoint Video Gaming

"Before entering a dangerous dungeon boss room, you save your progress. If your character perishes, you reload the snapshot and resume with exact health and inventory."

Time Machine Drive Snapshot System Administration

"Taking a snapshot of your laptop drive before performing a risky OS upgrade, allowing 1-click restore if anything breaks."

The Problem

Directly inspecting and saving private fields of an object breaks encapsulation; if internal representation changes, all backup code breaks.

The Solution

Delegate snapshot creation to the owner of the state (the Originator). Only the Originator can store and restore state from the Memento object.

Key Participants & Architectural Roles

Originator
Can produce snapshots of its state and restore its state from a memento
Memento
Passive data container that holds a snapshot of originator’s state
Caretaker
Knows when and why to capture the originator’s state, and keeps memento history

Code Samples (Traditional OOP vs Functional Programming)

Available in C++, Python, and Java

Paradigm Contrast: Traditional OOP vs Functional / Data-Oriented

In OOP, Memento uses opaque snapshot objects. In Functional Programming, Memento is completely unnecessary: state is immutable and persistent, meaning previous states are retained automatically as historical values.

Advantages

  • ✓ Produces snapshots of the object’s state without violating encapsulation
  • ✓ Simplifies originator’s code by letting caretaker maintain the history of the originator’s state

Trade-offs

  • ✗ Consumes significant RAM if clients create mementos too often without discarding old ones

When to Apply

  • → When you want to produce snapshots of the object’s state to be able to restore a previous state of the object (Undo/Redo)
  • → When direct access to the object’s fields/getters/setters violates its encapsulation

When to Avoid

  • ! When object state is massive and changes infrequently