在未来,时间旅行将被发明,备忘录是时间旅行的关键。基本上,他要做的是允许一个对象转换成状态。 在下面的例子,你可以时间旅行到你生命的任何时间,你可以重启去你以前去过的时代。
备忘录模式类图
备忘录模式Java代码
package designpatterns.memento;import java.util.List;import java.util.ArrayList;class Life { private String time; public void set(String time) { System.out.println("Setting time to " + time); this.time = time; } public Memento saveToMemento() { System.out.println("Saving time to Memento"); return new Memento(time); } public void restoreFromMemento(Memento memento) { time = memento.getSavedTime(); System.out.println("Time restored from Memento: " + time); } public static class Memento { private final String time; public Memento(String timeToSave) { time = timeToSave; } public String getSavedTime() { return time; } }} public class You { public static void main(String[] args) { List savedTimes = new ArrayList(); Life life = new Life(); //time travel and record the eras life.set("2000 B.C."); savedTimes.add(life.saveToMemento()); life.set("2000 A.D."); savedTimes.add(life.saveToMemento()); life.set("3000 A.D."); savedTimes.add(life.saveToMemento()); life.set("4000 A.D."); life.restoreFromMemento(savedTimes.get(0)); }}