added memento example
This commit is contained in:
parent
42c63045b0
commit
73129fd4c1
19
src/learn/simple_memento/CareTaker.java
Normal file
19
src/learn/simple_memento/CareTaker.java
Normal 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");
|
||||
}
|
||||
}
|
||||
}
|
19
src/learn/simple_memento/Main.java
Normal file
19
src/learn/simple_memento/Main.java
Normal 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);
|
||||
}
|
||||
}
|
35
src/learn/simple_memento/Originator.java
Normal file
35
src/learn/simple_memento/Originator.java
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user