public class Main {
public static void main(String[] args) {
RoleOriginator role = new RoleOriginator();
role.display();
role.fight();
role.display();
System.out.println("保存上面的快照");
RoleStateCaretaker caretaker = new RoleStateCaretaker();
caretaker.setMemento(role.saveState());
role.fight();
role.fight();
role.fight();
role.fight();
role.display();
System.out.println("准备恢复快照");
role.recoveryState(caretaker.getMemento());
role.display();
}
}
public class RoleOriginator {
/**
* 生命力,会下降
*/
private int live = 100;
/**
* 攻击力,会上涨
*/
private int attack = 50;
public int getLive() {
return live;
}
public void setLive(int live) {
this.live = live;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public void display(){
System.out.println("开始=========");
System.out.println("生命力:"+live);
System.out.println("攻击力:"+attack);
System.out.println("结束=========");
}
public void fight(){
//攻击力会上涨
this.attack = attack+2;
//打架生命力会下降
this.live = live - 10;
}
/**
* 保存快照,存储状态
* @return
*/
public RoleStateMemento saveState(){
return new RoleStateMemento(live,attack);
}
/**
* 恢复
*/
public void recoveryState(RoleStateMemento memento){
this.attack = memento.getAttack();
this.live = memento.getLive();
}
}
public class RoleStateCaretaker {
private RoleStateMemento memento;
public RoleStateMemento getMemento() {
return memento;
}
public void setMemento(RoleStateMemento memento) {
this.memento = memento;
}
}
public class RoleStateMemento {
/**
* 生命力,会下降
*/
private int live;
/**
* 攻击力,会上涨
*/
private int attack ;
public RoleStateMemento(int live, int attack) {
this.live = live;
this.attack = attack;
}
public int getLive() {
return live;
}
public void setLive(int live) {
this.live = live;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
}