Skip to content

Memento Pattern — Short Notes

Save and restore an object's state

Builds on Encapsulation

Stage 3advanced1 min read

Problem Overview

The TextEditor class keeps its text in one content field. write() replaces that text.
The class has no way to:

  • Save previous states.
  • Restore older versions of the content.

So undo/redo is impossible.


Design Issues

  1. No State Preservation

    • Each call to write() replaces content, so the old text is lost.
    • There is no way to go back to a previous state.
  2. Encapsulation Violation Risk

    • If we add undo/redo inside TextEditor, other code would need to see its internal state.
    • This would break encapsulation (the data should stay private). It would also break the Single Responsibility Principle (SRP), which says a class should do one job. The editor should not manage history.
  3. Tight Coupling

    • If TextEditor also managed history, editing and history code would mix in one class. It would be harder to maintain or extend.

Core Problem

How can we add undo/redo, or restore an old state, without exposing the internal state of TextEditor and without violating SRP?

The Memento Pattern solves this by introducing:

  • A separate Memento class (EditorMemento in After) to hold snapshots of the editor’s state.
  • A Caretaker (e.g., a History class) to keep the mementos.

Each class has one job. The editor's data stays private.

In this topic

Before code2 files

Before/TextEditor.java19 linesGitHub
package DesignPatterns.BehaviouralPatterns.MementoPattern.Before;/** * A text editor where the user can undo changes, such as text addition, deletion or formatting. The editor stores * snapshots of its state (text content) after each change, enabling the user to revert to previous state. */public class TextEditor {    private String content;    public void write(String text) {        this.content = text;    }    public String getContent() {        return content;    }}
Before/TextEditorMain.java12 linesGitHub
package DesignPatterns.BehaviouralPatterns.MementoPattern.Before;public class TextEditorMain {    public static void main(String[] args) {        TextEditor editor = new TextEditor();        editor.write("Hello World");        editor.write("Hello Everyone");        // Problem -> Undo the last write!        System.out.println("Printing the content : " + editor.getContent());    }}

Done with this topic?

How well do you know it?

PreviousSequential Request Processing