In modern application design, preserving and restoring previous states—such as implementing undo/redo functionality, transactional rollbacks, or snapshot checkpoints—is a common necessity. However, exposing internal fields to external objects breaks encapsulation. The Memento Design Pattern solves this challenge cleanly by capturing and externalizing an object’s internal state so that it can be restored later without violating data encapsulation boundaries.
Key Components & Architecture
Originator: The core object containing the active state. It creates a snapshot of its internal state into a Memento object and restores its state when supplied with a previously saved Memento.
Memento: An immutable value object that securely encapsulates the internal state of the Originator. It provides restricted visibility to protect state data from unauthorized modification.
Caretaker: Responsible for tracking and storing Memento instances (e.g., maintaining an undo stack or history list) without inspecting or modifying the contents of the mementos.
Implementation Best Practices & Guidelines
Protect Encapsulation: Ensure the Memento provides a wide interface to the Originator (allowing full state extraction/restoration) and a narrow interface to the Caretaker (preventing access to internal state variables).
Enforce Immutability: Design Memento objects as immutable state containers so saved checkpoints cannot be altered after creation.
Manage State Footprint: Storing full snapshots can consume significant memory. For large objects, consider delta-based state capture or limiting the history stack capacity.
Leverage Inner Classes: Defining the Memento as a private inner class within the Originator allows seamless private field access while keeping the state strictly inaccessible to external consumers.
Why Proper Implementation Matters
Zero Encapsulation Violation: Internal state details remain strictly private to the Originator, keeping class boundaries pristine.
Simplified Originator Architecture: The Originator does not need to manage history management, stack structures, or archival logic—the Caretaker handles these lifecycle operations.
Predictable Undo/Redo Mechanisms: Simplifies complex multi-step state rollbacks across enterprise desktop, mobile, and web applications.
Recommended Next Videos
Continue your deep dive into the Memento pattern and behavioral design patterns with these related tutorials from our channel:
The Memento Design Pattern is a behavioral pattern used to capture and restore the internal state of an object without exposing its internal structure. While class diagrams show the static relationships between the Originator, Memento, and Caretaker, a Sequence Diagram illustrates the dynamic runtime interactions, message exchanges, and exact chronological order required to save and restore state reliably.
Runtime Sequence: Saving and Restoring State
Phase 1: Snapshot Creation: When an event triggers a checkpoint, the Caretaker requests the Originator to create a snapshot (e.g., via createMemento()).
Phase 2: Memento Instantiation: The Originator instantiates a new Memento object, passing its current private state fields into the memento constructor.
Phase 3: State Storage: The newly created memento is returned to the Caretaker, which safely holds or pushes it onto a history stack without inspecting its contents.
Phase 4: State Restoration (Undo): When an undo operation is requested, the Caretaker retrieves the memento from history and calls restore(memento) on the Originator, which rehydrates its internal fields.
Key Roles Along the Interaction Lifeline
Caretaker Lifeline: Initiates save and restore operations, managing checkpoint lifecycles while remaining completely ignorant of the state data inside the mementos.
Originator Lifeline: Creates mementos reflecting its current internal state and accepts past mementos to restore previous configurations.
Memento Lifeline: Represents the immutable snapshot object created dynamically during the save phase and passed back during the restore phase.
Why Sequence Understanding Matters
Encapsulation Protection: The sequence demonstrates visually that the Caretaker never interacts directly with the private data of the Memento or Originator.
Clear Separation of Concerns: Shows the clean separation between history management (Caretaker) and actual business state tracking (Originator).
Predictable State Transitions: Clarifies the message flows required to build robust undo/redo stacks, transactional rollback checkpoints, and snapshot systems.
Recommended Next Videos
Continue your deep dive into the Memento pattern and behavioral design patterns with these related tutorials from our channel:
Understanding the Memento Design Pattern Class Diagram
The Memento Design Pattern is a behavioral pattern that allows an application to capture and restore the internal state of an object without exposing its private implementation details. To implement this pattern cleanly in object-oriented systems, it is essential to master its structural architecture. A Unified Modeling Language (UML) class diagram provides a clear blueprint detailing how the Originator, Memento, and Caretaker classes interact while preserving encapsulation boundaries.
Key Structural Components in UML
Originator: The primary business class containing mutable state. In the class diagram, it exposes methods such as createMemento() to produce state snapshots and restore(Memento) to restore past state.
Memento: The passive state container holding a snapshot of the Originator’s fields. It is modeled to have narrow visibility towards external components and wide access for the Originator.
Caretaker: The manager responsible for safe-keeping snapshots (e.g., maintaining an undo/redo stack or history collection). It never inspects, modifies, or accesses internal memento data.
Relationships and Architectural Roles
Dependency / Instantiation: The Originator instantiates and interacts with the Memento, populating it with snapshot data and consuming it during state restoration.
Aggregation / Association: The Caretaker holds an aggregation reference (often a List<Memento> or Stack<Memento>) to preserve historical checkpoints over time.
Encapsulation Shielding: The Caretaker interacts only with the Memento through a narrow interface (or treats it as an opaque token), ensuring private state attributes remain hidden.
Architectural Advantages
Encapsulation Preservation: Eliminates the need for public getters and setters on sensitive internal state fields purely for persistence or undo purposes.
Single Responsibility Principle (SRP): Keeps history tracking, stack management, and storage lifecycles isolated in the Caretaker, leaving the Originator focused strictly on core business rules.
Modular & Extensible: Checkpoint storage strategies (e.g., file caching, memory stacks, or distributed persistence) can be modified without altering the Originator.
Recommended Next Videos
Continue your deep dive into the Memento pattern and behavioral design patterns with these related tutorials from our channel:
Capturing and restoring state history is essential across various software systems—from document text editors and graphic design software to game checkpoints and multi-step transaction forms. The challenge lies in saving these snapshots without exposing an object's internal private fields. The Memento Design Pattern provides an elegant solution by encapsulating an object's state inside a dedicated snapshot without violating object-oriented encapsulation principles.
Practical Demonstration & Workflow
State Changes: The user performs actions (such as typing text or modifying document properties), which update the internal state of the Originator.
Taking Checkpoints: Before executing high-impact modifications, the application triggers a save point. The Originator packages its active attributes into an immutable Memento.
Safe Storage: The Caretaker receives the Memento and pushes it onto an undo stack, keeping track of history without inspecting what is inside the checkpoint.
Rolling Back: When an undo operation is requested, the Caretaker pops the latest snapshot from its stack and passes it back to the Originator to restore its prior state effortlessly.
Core Roles in the Demonstration
Originator: Maintains the active business state (e.g., text content, configuration settings) and possesses full knowledge of how to create and restore from snapshots.
Memento: Stores the snapshot data securely and immutably, ensuring external objects cannot tamper with the saved values.
Caretaker: Coordinates save and rollback requests and manages the history timeline (e.g., stack or list of mementos).
Architectural Advantages
Strict Encapsulation: Eliminates the bad practice of exposing private fields via public getters and setters solely for state persistence.
Simplified Business Logic: The Originator focuses purely on its domain tasks while delegating the history tracking lifecycle to the Caretaker.
Robust Undo/Redo Capabilities: Provides a predictable, decoupled foundation for implementing multi-level undo, rollback, and recovery workflows in enterprise applications.
Recommended Next Videos
Continue your deep dive into the Memento pattern and behavioral design patterns with these related tutorials from our channel:
In software development, managing state changes is a critical requirement across applications such as word processors, graphic design suites, game engines, and transactional workflows. Often, an application needs to roll back to a previous checkpoint. However, exposing an object’s private fields to an external history manager violates the fundamental principle of data encapsulation. The Memento Design Pattern addresses this problem by externalizing an object’s internal state into an opaque snapshot object, enabling rollback capabilities while keeping private implementation details hidden.
Core Concepts & Architecture
Encapsulation-Safe State Capture: The pattern allows state capture without requiring public getters and setters for private fields.
Three Key Collaborators: Coordinates state lifecycle across three distinct entities: the Originator, the Memento, and the Caretaker.
Dual-Interface Protection: A classic memento pattern uses a wide interface for the Originator (allowing full access to state data) and a narrow interface for the Caretaker (preventing access to internal state data).
Transactional Safety: Facilitates undo/redo operations and recovery checkpoints in long-running processes.
Primary Pattern Participants
Originator: The business object that possesses an internal state. It is responsible for creating a Memento holding a snapshot of its state and using past Mementos to restore itself.
Memento: An immutable object that encapsulates the state snapshot of the Originator. It restricts direct access from external classes to safeguard encapsulation.
Caretaker: The manager responsible for storing and tracking snapshots (e.g., maintaining an undo stack). It never inspects or mutates the internal contents of the mementos.
Architectural Advantages
Preserves Information Hiding: Keeps the Originator's private implementation encapsulated, avoiding code smell like exposing private state via getters.
Decouples Lifecycle and Storage: The Originator does not need to handle history management, arrays, or stacks—the Caretaker handles storage lifecycles independently.
Predictable State Rollbacks: Provides a standardized, clean foundation for multi-level undo, rollback mechanisms, and system checkpoint recovery.
Recommended Next Videos
Continue your deep dive into the Memento pattern and behavioral design patterns with these related tutorials from our channel:
The Memento Design Pattern is a foundational Gang of Four (GoF) behavioral pattern engineered to capture and externalize an object’s internal state so that it can be restored later without violating encapsulation. Understanding the core takeaways, essential rules, and trade-offs of this pattern enables software engineers to implement clean undo/redo mechanisms, transaction rollbacks, and recovery checkpoints in enterprise systems.
Core Concepts & Architecture
Encapsulation Integrity: The primary objective of the Memento pattern is safeguarding encapsulation boundaries. State details remain private to the Originator and completely opaque to the Caretaker.
Distinct Separation of Roles: The pattern relies on three distinct collaborators: the Originator (state owner), the Memento (state snapshot), and the Caretaker (state manager).
Wide vs. Narrow Interface: A standard memento architecture presents two interfaces: a wide interface accessible only to the Originator (allowing full state extraction/restoration) and a narrow interface to the Caretaker (preventing inspection or mutation of state fields).
Immutability of Snapshots: Once a Memento is created, its captured state should never be modified.
When Should You Apply the Memento Pattern?
Undo and Redo Functionality: When building interactive user interfaces, text editors, canvas applications, or graphic editors that require multi-level rollbacks.
Transactional Integrity & Rollback: When an operation may fail midway and requires rolling back to a known stable snapshot without re-instantiating the entire object.
Checkpoint and State Persistence: When saving game progress, multi-step wizard form sessions, or system configuration recovery points.
Advantages & Trade-Offs
Zero Exposure of Private Data: Eliminates antipatterns like exposing internal fields via public getters and setters solely for snapshotting.
Simplified Originator Code: Offloads checkpoint storage, history management, and stack tracking entirely to the Caretaker.
Memory Footprint Consideration: Storing numerous full-state snapshots can consume substantial memory. For high-volume states, consider delta-based storage or limiting history capacity.
Recommended Next Videos
Continue your deep dive into the Memento pattern and behavioral design patterns with these related tutorials from our channel: