备忘录模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
对于一个对象状态的保存,我们可能只要保存他的一部分,那么就需要一个备忘类来封装这一部分属性。由对象自己来对这部分属性进行封装保存,也就是备份。并且由对象自己来实现恢复操作调用备份类来恢复。
不如来看游戏角色类,他实现了备份操作:将需要的属性备份到备份类中,并实现了恢复操作从备份类中恢复数据:
public class GameRole {
private int vit;
private int atk;
private int def;
public void setVit(int v) {
vit = v;
}
public int getVit() {
return vit;
}
public void setAtk(int a) {
atk = a;
}
public int getAtk() {
return atk;
}
public void setDef(int d) {
def = d;
}
public int getDef() {
return def;
}
public RoleStateMemento saveState() {
return new RoleStateMemento(vit, atk, def);
}
public void recoveryState(RoleStateMemento memento) {
this.vit = memento.getVit();
this.atk = memento.getAtk();
this.def = memento.getDef();
}
public void getInitState() {
this.vit = 100;
this.atk = 100;
this.def = 100;
}
public void stateDisplay() {
System.out.println("角色当前状态:");
System.out.println("Vitality: " + getVit());
System.out.println("Attack: " + getAtk());
System.out.println("Defense: " + getDef());
}
public void fight() {
this.vit = 0;
this.atk = 100;
this.def = 100;
}
}
角色其实状态是满状态100。战斗后生命值变为0。
来看备份类:
public class RoleStateMemento {
private int vit;
private int atk;
private int def;
public RoleStateMemento(int vit, int atk, int def) {
this.atk = atk;
this.vit = vit;
this.def = def;
}
public void setVit(int v) {
vit = v;
}
public int getVit() {
return vit;
}
public void setAtk(int a) {
atk = a;
}
public int getAtk() {
return atk;
}
public void setDef(int d) {
def = d;
}
public int getDef() {
return def;
}
}
备份类只是对角色的一些属性进行了封装。
既然我们要将备份保存下来,就需要管理这个备份类,我的设想是甚至可以在备份管理类中建个list或者map,按时间顺序或者建档名来管理角色备份数据。
这里只实现了单备份数据的存取:
public class RoleStateCaretaker {
private RoleStateMemento memento;
public void setMemento(RoleStateMemento memento) {
this.memento = memento;
}
public RoleStateMemento getMemento() {
return memento;
}
}
最后贴下主程序:
GameRole maliao = new GameRole();
maliao.getInitState();
maliao.stateDisplay();
RoleStateCaretaker stateAdmin = new RoleStateCaretaker();
stateAdmin.setMemento(maliao.saveState());
maliao.fight();
maliao.stateDisplay();
maliao.recoveryState(stateAdmin.getMemento());
maliao.stateDisplay();
stateAdmin.setMemento(maliao.saveState());即由管理类来管理备份类。