diff --git a/src/learn/simple_memento/CareTaker.java b/src/learn/simple_memento/CareTaker.java new file mode 100644 index 0000000..3d88810 --- /dev/null +++ b/src/learn/simple_memento/CareTaker.java @@ -0,0 +1,19 @@ +package learn.simple_memento; + +import java.util.Stack; + +public class CareTaker { + private final Stack snapshots = new Stack<>(); + + public void save(Originator.Memento memento) { + snapshots.push(memento); + } + + public void revert(Originator originator) { + if (!snapshots.isEmpty()) { + originator.setMemento(snapshots.pop()); + } else { + System.out.println("No saved memento to revert"); + } + } +} diff --git a/src/learn/simple_memento/Main.java b/src/learn/simple_memento/Main.java new file mode 100644 index 0000000..12d137f --- /dev/null +++ b/src/learn/simple_memento/Main.java @@ -0,0 +1,19 @@ +package learn.simple_memento; + +public class Main { + public static void main(String[] args) { + Originator originator = new Originator(); + CareTaker careTaker = new CareTaker(); + + originator.setState("blue"); + originator.setState("red"); + careTaker.save(originator.createMemento()); + originator.setState("yellow"); + careTaker.save(originator.createMemento()); + originator.setState("white"); + + careTaker.revert(originator); + careTaker.revert(originator); + careTaker.revert(originator); + } +} diff --git a/src/learn/simple_memento/Originator.java b/src/learn/simple_memento/Originator.java new file mode 100644 index 0000000..76304ef --- /dev/null +++ b/src/learn/simple_memento/Originator.java @@ -0,0 +1,35 @@ +package learn.simple_memento; + +public class Originator { + private String state; + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + System.out.println("[Originator] Setting state to " + state); + } + + public Memento createMemento() { + return new Memento(state); + } + + public void setMemento(Memento memento) { + state = memento.getSavedState(); + System.out.println("[Originator] State after restoring from memento: " + state); + } + + public class Memento { + private final String state; + + public Memento(String state) { + this.state = state; + } + + public String getSavedState() { + return state; + } + } +}