步骤一:建立原始类Original
public class Original {
//需要保存的属性value
private String value;
//创建备忘录
public Memento createMemento() {
return new Memento(value);
}
//存储值
public void restoreMemento(Memento memento) {
this.value=memento.getValue();
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Original(String value) {
super();
this.value = value;
}
}
步骤二:建立备忘录类 Memento
public class Memento {
private String value;
public Memento(String value) {
this.value=value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
步骤三:建立存储备忘录的类 Storage
public class Storage {
private Memento memento;
public Storage(Memento memento) {
this.memento = memento;
}
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
步骤四:测试
public class Test {
public static void main(String[] args) {
Original original =new Original("egg");
Storage storage =new Storage(original.createMemento());
System.out.println("初始化状态为:"+original.getValue());
original.setValue("niu");
System.out.println("修改后的状态"+original.getValue());
original.restoreMemento(storage.getMemento());
System.out.println("恢复后的状态:"+original.getValue());
}
}