// 角色public class Role {// 体力、攻击、防御 private int vit; private int ack; private int def;// 状态显示 public void StateDisplay(){ System.out.println("角色当前状态:"); System.out.println("体力:"+this.vit); System.out.println("攻击:"+this.ack); System.out.println("防御:"+this.def); }// 获得初始状态,通常来自本机磁盘或远程数据库 public void GetInitState(){ this.vit=100; this.ack=100; this.def=100; }// 战斗 public void Fight(){ this.vit=0; this.ack=0; this.def=0; }// 保存角色状态 public RoleStateMemento SaveState(){ return new RoleStateMemento(this.vit, this.ack, this.def); }// 恢复角色状态 public void RevoceryState(RoleStateMemento memento){ this.vit = memento.getVit(); this.ack = memento.getAtk(); this.def = memento.getDef(); } public int getVit() { return vit; } public void setVit(int vit) { this.vit = vit; } public int getAck() { return ack; } public void setAck(int ack) { this.ack = ack; } public int getDef() { return def; } public void setDef(int def) { this.def = def; }}// 角色状态管理者类public class RoleStateCaretaker { public RoleStateMemento roleStateMemento;}// 角色状态存储类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; }}// 角色状态管理者类public class RoleStateCaretaker { // 角色状态 public RoleStateMemento roleStateMemento;}// 角色状态存储类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; }}public class Test { public static void main(String[] args) {// 大战Boss前 Role role = new Role(); role.GetInitState(); role.StateDisplay();// 存档 RoleStateCaretaker stateAdmin = new RoleStateCaretaker(); stateAdmin.roleStateMemento=role.SaveState();// 大战boss,没了 role.Fight(); role.StateDisplay();// 回档 role.RevoceryState(stateAdmin.roleStateMemento); role.StateDisplay(); }}