1 将对象信息保存起来,可以以后将该对象恢复在保存之前的状态。
被保存的类:
public class GameRole {
// 攻击力
public Integer aggressivity;
// 防御力
public Integer defensive;
public GameRole(Integer aggressivity, Integer defensive) {
this.aggressivity = aggressivity;
this.defensive = defensive;
}
// 改变状态
public void fight() {
this.aggressivity = 0;
this.defensive = 0;
}
public RoleStateMemento saveState() {
return new RoleStateMemento(this.aggressivity, this.defensive);
}
public void recoveryState(RoleStateMemento roleStateMemento) {
this.aggressivity = roleStateMemento.getGameRole().aggressivity;
this.defensive = roleStateMemento.getGameRole().defensive;
}
public void displayer() {
System.out.println(aggressivity + " " + defensive);
}
}
信息存储箱
public class RoleStateMemento {
private GameRole gameRole;
public RoleStateMemento(Integer aggressivity, Integer defensive) {
gameRole = new GameRole(aggressivity, defensive);
}
public GameRole getGameRole() {
return gameRole;
}
public void setGameRole(GameRole gameRole) {
this.gameRole = gameRole;
}
}
信息管理者
public class RoleStateCareTaker {
private RoleStateMemento roleStateMemento;
public RoleStateMemento getRoleStateMemento() {
return roleStateMemento;
}
public void setRoleStateMemento(RoleStateMemento roleStateMemento) {
this.roleStateMemento = roleStateMemento;
}
}
测试:
public class TextMain {
public static void main(String[] args) {
GameRole gameRole = new GameRole(10, 10);
RoleStateCareTaker roleStateCareTaker = new RoleStateCareTaker();
RoleStateMemento roleStateMemento = gameRole.saveState();
roleStateCareTaker.setRoleStateMemento(roleStateMemento);
gameRole.displayer();
gameRole.fight();// 状态改变
gameRole.displayer();
gameRole.recoveryState(roleStateCareTaker.getRoleStateMemento());
gameRole.displayer();
}
}