added memento example

This commit is contained in:
Louis Heredero 2024-11-04 09:54:18 +01:00
parent 42c63045b0
commit 73129fd4c1
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
3 changed files with 73 additions and 0 deletions

View File

@ -0,0 +1,19 @@
package learn.simple_memento;
import java.util.Stack;
public class CareTaker {
private final Stack<Originator.Memento> 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");
}
}
}

View File

@ -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);
}
}

View File

@ -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;
}
}
}