Memento Design Pattern in Java
Memento saves a snapshot of an object's state so you can go back to it later. It does this without breaking encapsulation.
Real life example
Save point in a video game, or Ctrl+Z in a text editor.
When to use
You need undo, rollback or restore features.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
public class Main {
public static void main(String[] args) {
Editor e = new Editor();
e.type("Hello");
Editor.Snapshot saved = e.save();
e.type(" World");
e.restore(saved);
System.out.println(e.getText()); // Hello
}
}
class Editor {
private String text = "";
void type(String t) { text += t; }
String getText() { return text; }
Snapshot save() { return new Snapshot(text); } // create memento
void restore(Snapshot s) { text = s.text; } // go back
static class Snapshot {
private final String text;
private Snapshot(String text) { this.text = text; }
}
}Output
Hello