# How to Implement the Memento Pattern for State Snapshot and Restoration in Java

> Learn to implement the Memento pattern in Java for effortless state snapshot and restoration. Capture and restore object states without exposing internal details.

- Repository: [Ilkka Seppälä/java-design-patterns](https://github.com/iluwatar/java-design-patterns)
- Tags: how-to-guide
- Published: 2026-02-27

---

**The Memento pattern lets an object capture its internal state without exposing implementation details, enabling state restoration and undo functionality.**

The Memento pattern is essential when you need to implement rollback functionality while keeping an object's implementation details hidden. In the **iluwatar/java-design-patterns** repository, this behavioral pattern is demonstrated through a celestial simulation where a `Star` object evolves over time and can revert to previous states. This implementation showcases how to implement the Memento pattern for state snapshot and restoration using three distinct roles: the Originator, the Memento, and the Caretaker.

## Understanding the Three Roles of the Memento Pattern

The Memento pattern relies on three collaborators to separate state management from business logic.

### Originator: The State Owner

The **Originator** holds the mutable state and can create snapshots of itself. In `com.iluwatar.memento.Star`, the class encapsulates `type`, `ageYears`, and `massTons` fields, providing `getMemento()` to capture state and `setMemento(StarMemento)` to restore it.

### Memento: The Opaque Snapshot

The **Memento** interface acts as an opaque token that hides the actual state data. The repository defines `StarMemento` as a marker interface in `com.iluwatar.memento.StarMemento`, while the concrete implementation `StarMementoInternal` remains a private inner class within `Star`. This design ensures that only the Originator can access the saved field values, maintaining strict encapsulation.

### Caretaker: The History Manager

The **Caretaker** requests snapshots from the Originator and stores them without inspecting their contents. The `App` class in `com.iluwatar.memento.App` demonstrates this role by using a `Stack<StarMemento>` to maintain a history of star states, enabling LIFO (Last-In-First-Out) undo behavior.

## Implementing Snapshot Creation in the Originator

The Originator implements two critical methods for state management. According to the source code in [`Star.java`](https://github.com/iluwatar/java-design-patterns/blob/main/Star.java), the `getMemento()` method creates a private `StarMementoInternal` instance, copies the current field values, and returns it typed as the `StarMemento` interface.

```java
// Inside Star.java
StarMemento getMemento() {
    var state = new StarMementoInternal();   // private inner class
    state.setAgeYears(ageYears);
    state.setMassTons(massTons);
    state.setType(type);
    return state;                            // returned as StarMemento
}

void setMemento(StarMemento memento) {
    var state = (StarMementoInternal) memento; // safe cast – only Star creates these
    this.type = state.getType();
    this.ageYears = state.getAgeYears();
    this.massTons = state.getMassTons();
}

```

## Managing History and Undo Operations

The Caretaker coordinates the snapshot workflow without violating encapsulation. In [`App.java`](https://github.com/iluwatar/java-design-patterns/blob/main/App.java), the implementation creates a `Star`, pushes mementos onto a stack after state changes, and pops them to restore previous states.

```java
public static void main(String[] args) {
    var history = new Stack<StarMemento>();

    var star = new Star(StarType.SUN, 10_000_000, 500_000);
    System.out.println(star);          // initial state
    history.add(star.getMemento());    // snapshot #1

    star.timePasses();                  // state changes (mutation occurs here)
    System.out.println(star);
    history.add(star.getMemento());    // snapshot #2

    // Undo to previous states
    while (!history.isEmpty()) {
        star.setMemento(history.pop());
        System.out.println("Restored: " + star);
    }
}

```

This approach stores opaque `StarMemento` objects that the Caretaker cannot modify or inspect, ensuring the `Star` class maintains control over its internal consistency.

## Architectural Flow of State Restoration

When implementing the Memento pattern for undo functionality, follow this sequence as demonstrated in the repository. This workflow ensures clean separation between state creation and storage while preserving encapsulation.

1. **Instantiate the Originator** – Create a `Star` with initial parameters (type, age, mass).
2. **Capture State** – Call `star.getMemento()` to receive an opaque snapshot.
3. **Store Snapshot** – Push the memento onto your chosen storage structure (the example uses `Stack` for natural undo ordering).
4. **Mutate State** – Invoke `star.timePasses()` or other business methods that change internal fields.
5. **Restore State** – Pop the memento and call `star.setMemento(memento)` to revert to the saved values.

## Summary

- **Encapsulation preservation**: The Memento pattern hides internal state details using an opaque interface (`StarMemento`), ensuring only the `Star` class can access saved field values.
- **Three-role architecture**: The Originator (`Star`) creates and restores snapshots, the Memento (`StarMementoInternal`) stores state, and the Caretaker (`App`) manages history.
- **Safe casting**: The `setMemento()` method performs a safe downcast to `StarMementoInternal` because only the `Star` class can instantiate this private inner class.
- **Flexible storage**: While the example uses a `Stack` for undo functionality, the Caretaker can use any collection or persistence mechanism to store mementos.

## Frequently Asked Questions

### What is the primary benefit of using the Memento pattern for state snapshot and restoration?

The primary benefit is **encapsulation preservation**. The pattern allows you to capture and restore an object's state without exposing its internal structure or breaking abstraction boundaries. External code (the Caretaker) can store snapshots but cannot inspect or modify the saved data, ensuring the Originator remains the sole authority over its state consistency.

### Why does the StarMemento interface contain no methods?

The `StarMemento` interface serves as a **marker interface** or opaque token. It provides a public type for the Caretaker to reference without revealing the `StarMementoInternal` implementation details. Since only the `Star` class needs to access the actual state data, the interface remains empty to prevent external manipulation of the snapshot contents.

### Can the Caretaker store mementos in a database instead of memory?

Yes, the Caretaker can use any storage mechanism. Because the `StarMemento` interface is serializable by design (in this implementation it is a simple object), you could persist mementos to a database, file system, or distributed cache. The Caretaker only needs to maintain the ability to return the exact object to the Originator's `setMemento()` method later.

### How does the Originator ensure type safety when restoring from a memento?

The `Star` class ensures type safety through **package-private or private scope control**. Since `StarMementoInternal` is a private inner class within `Star`, only `Star` instances can create or cast these objects. When `setMemento(StarMemento memento)` receives a memento, it safely casts to `StarMementoInternal` knowing that only valid snapshots created by its own `getMemento()` method could possibly be passed in.