设计模式-备忘录模式
备忘录模式看似不常见,其实挺常见的;比如著名的React 的时间旅行功能,就是备忘录模式的体现;还有一些游戏的存档、读档功能也是备忘录模式
例子:
先创建一个用于存档英雄血量的类: 时刻档类
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());
}
}