备忘录模式主要用于记录历史操作以及操作撤回等。重写例子时对书中做了一些更改,例如
RoleStateCaretaker里存放的Memento改成了List,这样可以模拟多次撤回的操作,比如word文档就可以撤回多次,如果只有一个Memento,只能回滚一次。
UML图
代码结构
public class Client {
public static void main(String[] args) {
//大战boss前
GameRole lixiaoyao = new GameRole(100, 100, 100);
lixiaoyao.stateDisplay();
//保存进度
RoleStateCaretaker stateAdmin = new RoleStateCaretaker();
stateAdmin.getMementos().add(lixiaoyao.saveState());
//大战boss
lixiaoyao.fight();
lixiaoyao.stateDisplay();
stateAdmin.getMementos().add(lixiaoyao.saveState());
//大战boss
lixiaoyao.fight();
lixiaoyao.stateDisplay();
stateAdmin.getMementos().add(lixiaoyao.saveState());
lixiaoyao.recoverState(stateAdmin.getMementos().get(1)); //回滚到第一次战斗后的状态
lixiaoyao.stateDisplay();
}
}
public class GameRole {
private int vit;
private int atk;
private int def;
public GameRole(int vit, int atk, int def) {
this.vit = vit;
this.atk = atk;
this.def = def;
}
public int getvit() {
return vit;
}
public void setvit(int vit) {
this.vit = vit;
}
public int getAtk() {
return atk;
}
public void setAtk(int atk) {
this.atk = atk;
}
public int getDef() {
return def;
}
public void setDef(int def) {
this.def = def;
}
//保存角色状态
public RoleStateMemento saveState() {
return new RoleStateMemento(vit, atk, def);
}
//恢复角色状态
public void recoverState(RoleStateMemento memento) {
this.vit = memento.getvit();
this.atk = memento.getAtk();
this.def = memento.getDef();
}
public void stateDisplay() {
System.out.println("角色当前状态:");
System.out.println("体力" + this.vit);
System.out.println("攻击力" + this.atk);
System.out.println("防御力" + this.def);
System.out.println("-----------------------");
}
public void fight() {
this.vit -= 10;
this.atk -= 10;
this.def -= 10;
}
}
public class RoleStateCaretaker {
List<RoleStateMemento> mementos = new ArrayList<>();
public List<RoleStateMemento> getMementos() {
return mementos;
}
public void setMementos(List<RoleStateMemento> mementos) {
this.mementos = mementos;
}
}
public class RoleStateMemento {
private int vit;
private int atk;
private int def;
public RoleStateMemento(int vit, int atk, int def) {
super();
this.vit = vit;
this.atk = atk;
this.def = def;
}
public int getvit() {
return vit;
}
public void setvit(int vit) {
this.vit = vit;
}
public int getAtk() {
return atk;
}
public void setAtk(int atk) {
this.atk = atk;
}
public int getDef() {
return def;
}
public void setDef(int def) {
this.def = def;
}
}
运行结果