public class MementoTest1 { public static void main(String[] args) { GameRole lixiaoyao = new GameRole(); lixiaoyao.GetInitState(); lixiaoyao.StateDisplay(); RoleStateCaretaker stateAdmin = new RoleStateCaretaker(); stateAdmin.setMemento(lixiaoyao.SaveState()); lixiaoyao.Fight(); lixiaoyao.StateDisplay(); lixiaoyao.RecoveryState(stateAdmin.getMemento()); lixiaoyao.StateDisplay(); System.out.println(); } } class GameRole { private int vit; public int getVitality() { return vit; } public void setVitality(int vit) { this.vit = vit; } private int atk; public int getAttack() { return atk; } public void setAttack(int atk) { this.atk = atk; } private int def; public int getDefense() { return def; } public void setDefense(int def) { this.def = def; } 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 GetInitState() { this.vit = 100; this.atk = 100; this.def = 100; } public void Fight() { this.vit = 0; this.atk = 0; this.def = 0; } public RoleStateMemento SaveState() { return (new RoleStateMemento(vit,atk,def)); } public void RecoveryState(RoleStateMemento memento) { this.vit = memento.getVitality(); this.atk = memento.getAttack(); this.def = memento.getDefense(); } } 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; } public int getVitality() { return vit; } public void setVitality(int vit) { this.vit = vit; } public int getAttack() { return atk; } public void setAttack(int atk) { this.atk = atk; } public int getDefense() { return def; } public void setDefense(int def) { this.def = def; } } class RoleStateCaretaker { private RoleStateMemento memento; public RoleStateMemento getMemento() { return memento; } public void setMemento(RoleStateMemento memento) { this.memento = memento; } }