Java Omnibus
OOAD & Architecture / GoF patterns / Behavioral / Memento Pattern in Java
GoF Behavioral Java Order Management
GoF Pattern

Memento is useful when an object’s state must be captured and restored without exposing its internals broadly.

Capture and externalize an object’s internal state so the object can be restored later without violating encapsulation.

Intent

What the pattern is trying to do

Capture and externalize an object’s internal state so the object can be restored later without violating encapsulation.

Problem

What force creates the need

The system needs rollback, restore, or historical snapshots, but exposing full internal state publicly would weaken encapsulation.

Solution

How the pattern responds

Create a memento object that stores snapshot state while the originator controls what gets saved and restored.

Structure

How the moving parts fit together

An originator creates and restores mementos, while a caretaker holds them without depending on the originator’s internal details.

Java Example

Java example in the Order Management domain

Memento Pattern in Java example
package org.javaomnibus.ecommerce.gof.behavioral;

public final class DraftOrder {
    private String shippingAddress;

    public DraftOrder(String shippingAddress) {
        this.shippingAddress = shippingAddress;
    }

    public OrderMemento save() {
        return new OrderMemento(shippingAddress);
    }

    public void restore(OrderMemento memento) {
        this.shippingAddress = memento.shippingAddress();
    }
}

public record OrderMemento(String shippingAddress) {}
Code Walkthrough

Step by step

  1. DraftOrder controls what state enters the snapshot.
  2. A caller can keep snapshots without manipulating internal fields directly.
  3. That preserves a cleaner boundary around object state.
  4. Memento earns its place when restore semantics matter, not when simple reassignment would do.
When To Use

Where this pattern helps

  • When undo, restore, or checkpoint behavior matters
  • When you need snapshots without exposing internal structure broadly
When Not To Use

When a simpler design is better

  • When state is simple and explicit reassignment is enough
  • When snapshots are too large or too frequent for the performance budget
Trade-Offs

What this pattern costs

  • Snapshot storage can be expensive
  • Complex mutable graphs make correct restore semantics harder
Modern Relevance

How this fits today

Memento is less common than Strategy or Observer, but it remains useful in editors, workflows, drafts, recovery features, and stateful domain tools.

Common Misuse

Where teams get it wrong

Capturing oversized object graphs as mementos without clear restore requirements can create memory cost without real product value.

Related Patterns

Compare with nearby choices


What To Read Next