From 73129fd4c14647632a0456d6a0b25b5a328ddecc Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Mon, 4 Nov 2024 09:54:18 +0100 Subject: [PATCH] added memento example --- src/learn/simple_memento/CareTaker.java | 19 +++++++++++++ src/learn/simple_memento/Main.java | 19 +++++++++++++ src/learn/simple_memento/Originator.java | 35 ++++++++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 src/learn/simple_memento/CareTaker.java create mode 100644 src/learn/simple_memento/Main.java create mode 100644 src/learn/simple_memento/Originator.java 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; + } + } +}