例子:
public class Memento {
// 英雄血量
private int bloodState;
public Memento(int bloodState){
this.bloodState = bloodState;
}
public int getState(){
return bloodState;
}
}
public class Hero {
// 初始一千点血
private int bloodState = 1000;
// 掉血
public void decrease(int dec){
this.bloodState -= dec;
}
// 加血
public void increase(int inc) {
this.bloodState += inc;
}
public int getBloodState() {
return bloodState;
}
// 存档
public Memento saveStateToMemento(){
return new Memento(this.bloodState);
}
// 读档
public void getStateFromMemento(Memento Memento){
this.bloodState = Memento.getState();
}
}
public class MementoTaker {
private List<Memento> mementoList = new ArrayList<Memento>();
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) {
Hero hero = new Hero();
MementoTaker mementoTaker = new MementoTaker();
hero.decrease(100);
hero.increase(50);
mementoTaker.add(hero.saveStateToMemento());
hero.decrease(100);
mementoTaker.add(hero.saveStateToMemento());
hero.increase(10);
System.out.println("Current State: " + hero.getBloodState());
hero.getStateFromMemento(mementoTaker.get(0));
System.out.println("First saved State: " + hero.getBloodState());
hero.getStateFromMemento(mementoTaker.get(1));
System.out.println("Second saved State: " + hero.getBloodState());
}
}