Course contentsShow
← Software Engineering
Lesson 301 of 1,9339. Behavioral Design PatternsFree lesson

The Memento Pattern: Capturing Object State

Learn how Memento enables undo/redo by capturing and restoring object state without violating encapsulation.

The Memento Pattern: Capturing Object State

What you'll learn: How the Memento pattern captures an object's internal state so you can restore it later—without breaking encapsulation.

The Core Problem

Imagine you're building a text editor with undo/redo functionality. You need to save the document's state at various points so users can revert changes. But how do you capture the internal state of a complex object without exposing all its private fields to the outside world?

What is the Memento Pattern?

The Memento pattern solves this by introducing a "snapshot" object that stores another object's state. Think of it like a save point in a video game: the game captures everything about your current progress without revealing the complex internal mechanics.

The pattern has three key players:

  1. Originator – the object whose state you want to save (like your document)
  2. Memento – the snapshot that holds the state
  3. Caretaker – manages the mementos (stores them, requests them) but never examines their contents

How It Preserves Encapsulation

The beauty of Memento is that only the Originator can read or write the Memento's contents. The Caretaker just holds onto these opaque snapshots. It's like handing someone a sealed envelope—they can store it and give it back, but they can't peek inside.

This enables undo/redo: every time the user makes a change, you create a memento. When they hit "undo," you restore from the previous memento. When they hit "redo," you move forward again.

Real-World Applications

  • Text editors: Every keystroke or action creates a memento
  • Database transactions: Rollback points capture state before changes
  • Game state management: Save/load functionality

Key Takeaway: The Memento pattern lets you capture and restore an object's internal state for undo/redo functionality while keeping that state private and preserving encapsulation.