1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| import java.util.ArrayList; import java.util.List;
class Memento { String state;
public Memento(String state) { this.state = state; }
public String getState() { return state; } }
class Originator { private String state;
public void setState(String state) { this.state = state; }
public String getState() { return state; }
public Memento saveStateToMemento() { return new Memento(state); }
public void getStateFromMemento(Memento Memento) { state = Memento.getState(); } }
class CareTaker { List<Memento> mementoList = new ArrayList<>();
public void add(Memento state) { mementoList.add(state); }
public Memento get(int index) { return mementoList.get(index); } }
public class MementoPatternDemo { public static void main(String[] args) { Originator originator = new Originator(); CareTaker careTaker = new CareTaker(); originator.setState("State #1"); originator.setState("State #2"); careTaker.add(originator.saveStateToMemento()); originator.setState("State #3"); careTaker.add(originator.saveStateToMemento()); originator.setState("State #4");
System.out.println("Current State: " + originator.getState()); originator.getStateFromMemento(careTaker.get(0)); System.out.println("First saved State: " + originator.getState()); originator.getStateFromMemento(careTaker.get(1)); System.out.println("Second saved State: " + originator.getState()); } }
|