momento-pattern
Definition
Purpose
Key Roles
Role
Description
Java Example
// Memento: stores state
class EditorMemento {
private final String content;
EditorMemento(String content) { this.content = content; }
String getContent() { return content; }
}
// Originator: creates/restores mementos
class Editor {
private String content = "";
void type(String words) { content += words; }
String getContent() { return content; }
EditorMemento save() { return new EditorMemento(content); }
void restore(EditorMemento memento) { content = memento.getContent(); }
}
// Caretaker: manages mementos
class History {
private final Stack<EditorMemento> history = new Stack<>();
void save(Editor editor) { history.push(editor.save()); }
void undo(Editor editor) {
if (!history.isEmpty()) editor.restore(history.pop());
}
}Pros ✅
Cons ❌
Real-world Analogy
Last updated