备忘录模式(Memento)
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将该对象恢复到原先保存的状态。
游戏角色:
//游戏角色
public class Actor {
//生命力
private int vit;
//攻击力
private int atk;
//防御力
private int def;
public Actor(int vit, int atk, int def) {
this.vit = vit;
this.atk = atk;
this.def = def;
}
//存储备忘录
public Memento creatMemento(){
return new Memento(this.vit,this.atk,this.def);
}
//得到备忘录,恢复数据
public void getMemento(Memento memento){
this.vit = memento.getVit();
this.atk = memento.getAtk();
this.def = memento.getDef();
}
@Override
public String toString() {
return "Actor{" +
"vit=" + vit +
", atk=" + atk +
", def=" + def +
'}';
}
//打Boss受伤
public void attack(){
this.vit = 0;
this.def = 0;
this.atk = 0;
}
}
备忘录:
//备忘录
public class Memento {
//生命力
private int vit;
//攻击力
private int atk;
//防御力
private int def;
public Memento(int vit, int atk, int def) {
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 MementoCareTaker {
private Memento memento;
public MementoCareTaker(Memento memento) {
this.memento = memento;
}
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
测试:
public class Test {
public static void main(String[] args) {
//初始化
Actor actor = new Actor(100, 100, 100);
System.out.println(actor.toString());
//保存
MementoCareTaker mementoCareTaker = new MementoCareTaker(actor.creatMemento());
//打Boss
actor.attack();
System.out.println(actor.toString());
//恢复
actor.getMemento(mementoCareTaker.getMemento());
System.out.println(actor.toString());
}
}
Actor{vit=100, atk=100, def=100}
Actor{vit=0, atk=0, def=0}
Actor{vit=100, atk=100, def=100}