在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后可将该对象恢复到原先保存的状态。
发起人、备忘录、管理者 组成备忘录模式
游戏进度备忘
class GameRole {
// 保存角色状态
public RoleStateMemento SaveState() {
return (new RoleStateMemento(vit,atk,def));
//恢复角色状态
public void RecoveryState(RoleStateMemento memeto) {
this.vit = memeto.Vitality;
this.atk = memeto.Attack;
this.def = memeto.Defense;
}
}
}
//角色状态存储箱
class RoleStateMemento {
private int vit;
private int atk;
private int def;
public RoleStateMemento(int vit,int atk,int def) {
this.vit = vit;
this.atk = atk;
this.def = def;
}
//生命力getset
//攻击力getset
//防御力getset..
}
// 角色状态管理类
class RoleStateCaretaker {
private RoleStateMemento memento;
//get set ...
}
//客户端代码
static void Main(String[] args) {
GameRole gr = new GameRole();
gr.GetInitState();
gr.StateDisplay();
RoleStateCaretaker stateAdmin = new RoleStateCaretaker();
stateAdmin.Memento = gr.SaveState();
gr.Fight();
gr.StateDisplay();
// 恢复之前状态
gr.RecoveryState(stateAdmin.Memento);
gr.Statedisplay();
}