Full Stack • Java • System Design • Cloud • AI Engineering

Memento Design Pattern in Java

Learn Memento Design Pattern in Java with Undo functionality, state snapshots, text editor examples, transaction rollback concepts, UML diagrams, Java implementation, enterprise use cases, and interview questions.

What You Will Learn

  • What is Memento Pattern?
  • Why Memento Pattern is Needed
  • Undo and Restore Operations
  • Snapshot Management
  • Java Implementation
  • Text Editor Example
  • Transaction Rollback Concepts
  • Enterprise Use Cases
  • Benefits and Limitations
  • Interview Questions

Introduction

Imagine you are working in:

Microsoft Word

Google Docs

VS Code

IntelliJ IDEA

You accidentally delete:

100 Lines Of Code

What do you do?

CTRL + Z

The application restores the previous state.

This is the idea behind the Memento Pattern.


What is Memento Pattern?

Memento is a Behavioral Design Pattern that captures and stores an object's internal state so it can be restored later.

Simple view:

Current State

↓

Save Snapshot

↓

Modify Object

↓

Restore Snapshot

Purpose of Memento Pattern

Primary goal:

Save State

Restore State

Without Violating Encapsulation

Real World Analogy

Think about video games.

Before fighting a boss:

Save Game

If you lose:

Load Saved Game

The saved game acts as a:

Memento

Problem Without Memento

flowchart LR
    A[User Changes Data]
    B[Old State Lost]
    C[Cannot Restore]

    A --> B
    B --> C

Once state changes, old data is gone forever.


Solution With Memento

flowchart LR
    A[Current State]
    B[Save Snapshot]
    C[Modify State]
    D[Restore Snapshot]

    A --> B
    B --> C
    C --> D

Previous state is preserved.


Memento Architecture

flowchart LR
    A[Originator]
    B[Memento]
    C[Caretaker]

    A --> B
    C --> B

Key Components

Originator

Object whose state must be saved.


Memento

Stores object state.


Caretaker

Manages saved snapshots.


UML Diagram

classDiagram

class Originator {
    +save()
    +restore()
}

class Memento

class Caretaker

Originator --> Memento
Caretaker --> Memento

Real Example

Text Editor

Current Text:

Hello

User changes:

Hello World

User presses:

Undo

Application restores:

Hello

Workflow

flowchart LR
    A[Write Text]
    B[Save Snapshot]
    C[Edit Text]
    D[Undo]
    E[Restore Previous State]

    A --> B
    B --> C
    C --> D
    D --> E

Step 1: Memento Class

public class EditorMemento {

    private final String content;

    public EditorMemento(
            String content) {

        this.content = content;
    }

    public String getContent() {

        return content;
    }
}

Step 2: Originator

public class TextEditor {

    private String content;

    public void setContent(
            String content) {

        this.content = content;
    }

    public String getContent() {

        return content;
    }

    public EditorMemento save() {

        return new EditorMemento(
                content);
    }

    public void restore(
            EditorMemento memento) {

        content =
                memento.getContent();
    }
}

Step 3: Caretaker

import java.util.Stack;

public class History {

    private Stack<EditorMemento> stack =
            new Stack<>();

    public void save(
            EditorMemento memento) {

        stack.push(memento);
    }

    public EditorMemento undo() {

        return stack.pop();
    }
}

Step 4: Client Code

public class MementoDemo {

    public static void main(
            String[] args) {

        TextEditor editor =
                new TextEditor();

        History history =
                new History();

        editor.setContent("Hello");

        history.save(
                editor.save());

        editor.setContent(
                "Hello World");

        System.out.println(
                editor.getContent());

        editor.restore(
                history.undo());

        System.out.println(
                editor.getContent());
    }
}

Output

Hello World

Hello

Execution Flow

sequenceDiagram

Client->>Editor: Save State

Editor-->>History: Memento

Client->>Editor: Modify State

Client->>History: Undo

History-->>Editor: Memento

Editor-->>Client: Restored State

Banking Example

Money Transfer Workflow

Before transfer:

Balance = 10000

Save snapshot.

After transfer:

Balance = 7000

If failure occurs:

Restore Balance = 10000

Banking Flow

flowchart LR
    A[Current Balance]
    B[Save Snapshot]
    C[Transfer Money]
    D[Failure]
    E[Restore Balance]

    A --> B
    B --> C
    C --> D
    D --> E

Insurance Example

Claim Processing

Before approval:

Claim Status = Pending

Save state.

After update:

Claim Status = Approved

Rollback if validation fails.


Insurance Flow

flowchart LR
    A[Pending Claim]
    B[Save State]
    C[Approve Claim]
    D[Validation Error]
    E[Restore Pending State]

    A --> B
    B --> C
    C --> D
    D --> E

Transaction Rollback Concept

Database transactions follow a similar idea.

BEGIN

UPDATE

COMMIT

or

BEGIN

UPDATE

ROLLBACK

Rollback restores previous state.


Transaction Flow

flowchart LR
    A[Transaction Start]
    B[Save State]
    C[Execute Changes]
    D[Commit]
    E[Rollback]

    A --> B
    B --> C
    C --> D
    C --> E

IDE Example

IntelliJ

VS Code

Eclipse

Every edit creates a snapshot.

Undo restores previous state.


Enterprise Examples

Banking

Account Rollback

Transaction Recovery

Insurance

Claim State Recovery

Policy Updates

E-Commerce

Order Modification

Cart Recovery

Gaming

Save Game

Load Game

Editors

Undo

Redo

Version History

Spring Framework Example

Spring Transactions conceptually use similar rollback mechanisms.

@Transactional
public void transferFunds() {

}

On failure:

Rollback

Previous state restored.


Benefits

✅ Supports Undo Functionality

✅ Preserves Object Encapsulation

✅ Easy State Restoration

✅ Simplifies Rollback Logic

✅ Improves Reliability


Limitations

❌ High Memory Usage

❌ Many Snapshots Can Consume Space

❌ Complex State Management

❌ Snapshot Serialization Cost


When To Use

Use Memento when:

  • Undo functionality is required
  • State restoration is needed
  • Rollback support is required
  • Version history is needed

When Not To Use

Avoid when:

  • Object state is very large
  • State restoration is unnecessary
  • Memory constraints are strict

Memento vs Command

Feature Memento Command
Purpose Save State Execute Action
Undo Snapshot Restore Reverse Action
Focus State Behavior

Memento vs Prototype

Feature Memento Prototype
Goal Restore State Clone Objects
Focus History Copy Creation
Usage Undo Object Duplication

Real Enterprise Architecture

flowchart LR
    A[Application]
    B[Originator]
    C[Memento Store]
    D[Restore Service]

    A --> B
    B --> C
    C --> D

Interview Questions

What is Memento Pattern?

A behavioral pattern that captures and restores an object's state.


What Problem Does It Solve?

Undo and rollback functionality.


What are the Main Components?

Originator

Memento

Caretaker

Real World Example?

Text Editor Undo Functionality.


Enterprise Example?

Transaction Rollback.


Does Memento Break Encapsulation?

No. State is restored without exposing internal details.


Difference Between Command and Memento?

Command stores actions.

Memento stores state.


Key Takeaways

  • Memento is a Behavioral Design Pattern.
  • Captures and restores object state.
  • Widely used for Undo and Rollback operations.
  • Consists of Originator, Memento, and Caretaker.
  • Common in editors, games, workflow engines, and transaction systems.
  • Supports history management without violating encapsulation.
  • Essential pattern for state recovery and versioning systems.