Course contentsShow
← Computer Science
Lesson 2298 of 2,87251. Design PatternsFree lesson

Memento Pattern

Capturing and externalizing an object's internal state to enable restoration without violating encapsulation.

Memento Pattern

What you'll learn: You'll discover how to save and restore an object's state without exposing its internal details.

What Problem Does It Solve?

Imagine you're working on a text editor with an undo feature. You need to save the document's state at various points so users can revert changes. But you don't want to expose the document's complex internal structure (text buffers, formatting data, cursor positions) to the undo manager—that would violate encapsulation and create tight coupling.

The Memento Pattern solves this by letting you capture and store an object's state in a separate "memento" object, which can later restore the original object—all without revealing internal details.

How It Works

The pattern involves three participants:

  • Originator: The object whose state you want to save (e.g., a TextEditor)
  • Memento: A snapshot that stores the originator's state (opaque to outsiders)
  • Caretaker: Manages when to save and restore states (e.g., an UndoManager), but never examines or modifies the memento's contents

Think of it like a save game system: the game (originator) creates a save file (memento) that the menu system (caretaker) stores. The menu doesn't need to understand the save file's internal format—it just knows how to trigger saves and loads.

Why It Matters

This pattern preserves encapsulation by keeping the originator's internals private. The caretaker can implement undo/redo, checkpoints, or rollback functionality without knowing implementation details. If the originator's structure changes, only the originator and memento need updates—the caretaker remains untouched.

Key Takeaway: The Memento Pattern captures an object's internal state in a separate memento object, enabling later restoration while maintaining encapsulation boundaries between the originator and its clients.