Behavioral Design Pattern

Memento Design Pattern in Java

Capture and restore an object's state without exposing its internal implementation.

In this lesson: Memento stores a snapshot that the originator can later restore. A caretaker keeps snapshots but does not modify their internal state.

Overview

final class Editor { private String text; void write(String text) { this.text = text; } Snapshot save() { return new Snapshot(text); } void restore(Snapshot snapshot) { text = snapshot.text(); } record Snapshot(String text) {} }

Implementation

Editor editor = new Editor();
editor.write("Version one");
Editor.Snapshot saved = editor.save();
editor.write("Version two");
editor.restore(saved);
Use Memento for undo and redo, editor history, checkpoints, drafts, and rollback of in-memory state.

When should you use it?

Use Memento for undo and redo, editor history, checkpoints, drafts, and safe restoration of in-memory state.

Next step: Continue with the Design Patterns course and explore the next pattern.