游戏角色有血条和蓝条,在大战boss前保存自身的状态(血量、蓝量),当大战之后血和蓝有所下降,将其恢复到原来的状态
/***
* @author shaofan
* @Description 备忘录模式解决游戏角色状态恢复问题
*/
public class Game {
public static void main(String[] args) {
GameRole role = new GameRole(100,100);
Caretaker caretaker = new Caretaker();
caretaker.setMemento(role.createMemento());
System.out.println(role);
role.setBlood(10);
role.setBlue(0);
System.out.println(role);
role.recover(caretaker.getMemento());
System.out.println(role);
}
}
class GameRole{
private int blood;
private int blue;
public GameRole(int blood,int blue){
this.blood = blood;
this.blue = blue;
}
public int getBlood() {
return blood;
}
public void setBlood(int blood) {
this.blood = blood;
}
public int getBlue() {
return blue;
}
public void setBlue(int blue) {
this.blue = blue;
}
@Override
public String toString() {
return "GameRole{" +
"blood=" + blood +
", blue=" + blue +
'}';
}
public Memento createMemento(){
return new Memento(blood,blue);
}
public void recover(Memento memento){
blood = memento.getBlood();
blue = memento.getBlue();
}
}
class Memento{
private int blood;
private int blue;
public Memento(int blood,int blue){
this.blood = blood;
this.blue = blue;
}
public int getBlood() {
return blood;
}
public void setBlood(int blood) {
this.blood = blood;
}
public int getBlue() {
return blue;
}
public void setBlue(int blue) {
this.blue = blue;
}
}
class Caretaker{
private Memento memento;
public void setMemento(Memento memento){
this.memento = memento;
}
public Memento getMemento(){
return memento;
}
}