Memento Design Pattern in Java
1. Introduction
The Memento Pattern is used to capture and restore an object’s state without exposing its internal details.
It is especially useful when you need undo/redo functionality in applications.
2. Real-World Analogy
Think of a video game save system:
- You save your progress (create a snapshot).
- Later, if you fail in the game, you can restore from that save point.
- The game doesn’t tell you how it stores the data, it just lets you go back.
3. Structure of Memento Pattern
- Originator → The object whose state needs to be saved.
- Memento → Stores the state of the Originator.
- Caretaker → Manages the saved states (mementos).
4. Custom Implementation Example
Let’s build a Text Editor with Undo Feature.
Step 1 – Memento Class
public class TextMemento {
private final String state;
public TextMemento(String state) {
this.state = state;
}
public String getState() {
return state;
}
}
Step 2 – Originator (TextEditor)
public class TextEditor {
private String text;
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
// Save current state to a memento
public TextMemento save() {
return new TextMemento(text);
}
// Restore state from a memento
public void restore(TextMemento memento) {
this.text = memento.getState();
}
}
Step 3 – Caretaker (History Manager)
import java.util.Stack;
public class History {
private Stack history = new Stack<>();
public void save(TextEditor editor) {
history.push(editor.save());
}
public void undo(TextEditor editor) {
if (!history.isEmpty()) {
editor.restore(history.pop());
}
}
}
Step 4 – Client Code
public class MementoPatternDemo {
public static void main(String[] args) {
TextEditor editor = new TextEditor();
History history = new History();
editor.setText("Version 1: Hello");
history.save(editor);
editor.setText("Version 2: Hello World");
history.save(editor);
editor.setText("Version 3: Hello World!!!");
System.out.println("Current: " + editor.getText());
// Undo
history.undo(editor);
System.out.println("After Undo: " + editor.getText());
history.undo(editor);
System.out.println("After Second Undo: " + editor.getText());
}
}
5. Output
Current: Version 3: Hello World!!!
After Undo: Version 2: Hello World
After Second Undo: Version 1: Hello
6. Advantages
- Provides undo/redo functionality easily.
- Preserves encapsulation since internal state isn’t exposed.
- Helps in building robust history management features.
7. Real-World Use Cases
- Text editors (undo/redo).
- Video games (save checkpoints).
- Graphic editing software (restore previous designs).
Database transactions (rollback functionality).
Next- Observer Design Pattern in Java