Introduction
Imagine you are building a text editor like Microsoft Word or Google Docs.
A user performs the following actions:
Type "Hello"
Type "Hello World"
Type "Hello World !!!"
Now the user presses:
Undo
The document should return to:
Hello World
Press Undo again:
Hello
Press Undo again:
Empty Document
To implement this feature, the application must remember previous states of the document.
A beginner might store copies manually:
string state1 = "";
string state2 = "Hello";
string state3 = "Hello World";
This works for small examples.
But what if the object contains:
Hundreds of fields
Complex configurations
Nested objects
Managing the state manually becomes difficult.
This is where the Memento Design Pattern helps.
What is the Memento Pattern?
The Memento Pattern is a behavioral design pattern that allows an object's state to be saved and restored without exposing its internal implementation details.
In simple words:
The Memento Pattern captures an object's current state so it can be restored later.Think of it as creating a snapshot of an object.
Real World Analogy
Imagine playing a video game.
Before fighting a difficult boss, you save the game.
Save Game
If you lose:
Load Saved Game
The game restores:
Health
Inventory
Position
Progress
Everything returns to the exact previous state.
The save file acts as a Memento.
Why Do We Need the Memento Pattern?
Consider a text editor.
Without Memento:
To implement undo, another class might directly access:
and store copies manually.
This creates several problems.
Problems Without Memento Pattern
1. Encapsulation Violation
External objects need access to internal state.
Internal details become exposed.
2. Complex State Management
Large objects become difficult to track manually.
3. Undo Logic Gets Scattered
Different classes may manage history differently.
4. Poor Maintainability
Changes to object structure may break state-saving logic.
Solution: Memento Pattern
The Memento Pattern introduces a dedicated object called a Memento.
The Memento stores snapshots of an object's state.
Instead of exposing internal details:
Object
│
▼
Memento
The state is stored safely and can be restored later.
Key Components of the Memento Pattern
The Memento Pattern usually contains three main components.
1. Originator
The object whose state needs to be saved.
Example:
Document
Game
Editor
2. Memento
Stores the snapshot of the originator's state.
3. Caretaker
Manages saved mementos.
Example:
Undo Manager
History Manager
Checkpoint Manager
Structure of the Memento Pattern
Originator
│
▼
Memento
Caretaker
│
Stores History
Example: Text Editor Undo System
Let's build a simple text editor.
Step 1: Create Memento Class
The Memento stores the document state.
Step 2: Create Originator
The Document can:
Save State
Restore State
Step 3: Create Caretaker
The Caretaker manages saved snapshots.
Step 4: Client Code
Output
Hello World
Hello World
Hello
In real implementations, undo is usually performed slightly differently to avoid restoring the current snapshot first, but this example demonstrates the core idea.
How the Memento Pattern Works
Let's understand the complete flow.
Step 1
The Originator creates a snapshot.
Step 2
The snapshot is stored.
Step 3
The object changes.
Step 4
Undo is requested.
Step 5
The Originator restores its previous state.
Key Idea Behind the Pattern
The most important idea is:
Save and restore an object's state without exposing its internal details.
The Caretaker manages history.
The Memento stores state.
The Originator restores state.
Each component has a clear responsibility.
Multiple Undo Levels
One major advantage of Memento is supporting multiple undo operations.
Example:
Version 1
Version 2
Version 3
Version 4
History:
Top
Version 4
Version 3
Version 2
Version 1
Undo:
Version 4 → Version 3
Version 3 → Version 2
Version 2 → Version 1
This is how most editors implement Undo.
Redo Functionality
Redo can be implemented using another stack.
Undo:
Current Stack
↓
Undo Stack
Redo:
Redo Stack
↓
Restore Again
Most modern applications use two stacks:
Undo Stack
Redo Stack
Memento vs Command Pattern
This is a very common interview question.
| Memento Pattern | Command Pattern |
|---|---|
| Stores state | Stores actions |
| Snapshot-based undo | Operation-based undo |
| Restores the previous state | Reverses the executed command |
| Focuses on object state | Focuses on user actions |
Example
Memento:
Save Entire Document State
Command:
Undo Insert Text Command
Both can implement Undo functionality but use different approaches.
Memento vs State Pattern
| Memento | State |
|---|---|
| Saves state history | Represents the current state |
| Used for restoration | Used for behavior changes |
| Snapshot-oriented | Behavior-oriented |
| Supports undo/rollback | Supports state transitions |
Advantages of the Memento Pattern
1. Preserves Encapsulation
Internal object details remain hidden.
2. Supports Undo Functionality
One of the most common uses.
3. Easy Rollback
Objects can return to previous states.
4. Cleaner State Management
State history is separated from business logic.
5. Simplifies Recovery
Useful for checkpoints and backups.
Disadvantages of the Memento Pattern
1. Memory Consumption
Large objects may require significant storage.
Example:
1000 Snapshots
Each = 5 MB
Total = 5 GB
2. Performance Overhead
Creating snapshots repeatedly may be expensive.
3. Complex History Management
Managing many snapshots can become difficult.
4. Not Suitable for Huge Objects
Full state copies may not always be practical.
Real World Applications
The Memento Pattern is widely used in:
Text editors
Graphic design software
Video game save systems
Database checkpoints
Version control systems
Workflow rollback systems
IDE undo/redo features
Configuration management systems
Transaction recovery systems
Many productivity applications rely heavily on Memento-like mechanisms.
Common Beginner Mistakes
1. Exposing Internal State Directly
Avoid allowing external classes to modify mementos.
Mementos should be treated as snapshots.
2. Saving Too Frequently
Creating excessive snapshots can waste memory.
3. Ignoring Memory Usage
Large systems may require optimized snapshot storage.
4. Confusing Memento with Command
Remember:
Memento → Save State
Command → Save Action
Simple Visualization
Without Memento:
Document
├── Current State
No History
Undo is difficult.
With Memento:
Document
│
▼
Memento 1
Memento 2
Memento 3
Memento 4
The document can return to any previous snapshot.
Summary
The Memento Design Pattern provides a way to capture and restore an object's state without violating encapsulation.
By introducing Mementos to store snapshots and Caretakers to manage history, the pattern makes features like undo, rollback, checkpoints, and version history easier to implement. It is especially useful when applications need to restore objects to previous states while keeping internal implementation details hidden.
Whenever you need to preserve and restore object state safely, the Memento Pattern offers a clean and structured solution.