package study.org;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
Model originator = new Model();
Storage storage = new Storage();
originator.setValue("State #1"); // first init value
storage.add(originator.saveStateToMemento());
originator.setValue("State #2");// second init value
storage.add(originator.saveStateToMemento());
System.out.println("Current State: " + originator.getValue());
originator.restoreMemento(storage.get(0));
System.out.println("First saved State: " + originator.getValue());
originator.restoreMemento(storage.get(1));
System.out.println("Second saved State: " + originator.getValue());
}
}
// 备忘
class Memento {
private String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
}
// 测试实体类
class Model {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Memento saveStateToMemento() {
return new Memento(value);
}
public void restoreMemento(Memento memento) {
this.value = memento.getState();
}
}
// 存储
class Storage {
private List<Memento> mementoList = new ArrayList<Memento>();
public void add(Memento state) {
mementoList.add(state);
}
public Memento get(int index) {
return mementoList.get(index);
}
}
网友评论