一、 定义
备忘录模式(Memento),在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。以后就可将该对象恢复到原先保存的状态。
当功能比较复杂,需要维护和记录的属性历史的类,或者需要保存的属性只是众多属性中的一小部分时,可以使用备忘录模式。
二、 结构图
三、 示例代码
package org.example.mementomodel;
public class GameRole {
private int atk;
private int vit;
private int def;
MementoRole mr;
public void setRoleState(int atk,int vit,int def){
this.atk = atk;
this.vit = vit;
this.def = def;
}
public void getRoleState(){
System.out.println("rolestate:atk= " + atk + ",vit=" + vit + ",def=" + def);
}
//保存状态
public MementoRole saveState(){
mr = new MementoRole(atk,vit,def);
return mr;
}
//恢复状态
public void recoverState(MementoRole mr){
this.atk =mr.getAtk();
this.vit = mr.getVit();
this.def = mr.getDef();
}
}
package org.example.mementomodel;
public class MementoRole {
private int atk;
private int vit;
private int def;
MementoRole(int atk,int vit,int def){
this.atk = atk;
this.vit = vit;
this.def = def;
}
public int getAtk() {
return atk;
}
public void setAtk(int atk) {
this.atk = atk;
}
public int getVit() {
return vit;
}
public void setVit(int vit) {
this.vit = vit;
}
public int getDef() {
return def;
}
public void setDef(int def) {
this.def = def;
}
}
package org.example.mementomodel;
public class MementoManager {
private MementoRole mr;
public MementoRole getMementoRole(){
return mr;
}
public void setMementoRole(MementoRole mr){
this.mr = mr;
}
}
package org.example.mementomodel;
public class MementoModelTest {
public static void main(String[] args) {
GameRole gr = new GameRole();
gr.setRoleState(20,40,60);
MementoManager mm = new MementoManager();
mm.setMementoRole(gr.saveState());
gr.setRoleState(10,20,30);
gr.getRoleState();
gr.recoverState(mm.getMementoRole());
gr.getRoleState();
}
}