设计模式之备忘录模式,memento

来源:互联网 发布:hashmap的hash算法key 编辑:程序博客网 时间:2024/05/17 03:45
package liu.memento.demo;
public class GameRole {
 
 private int vit;//生命力
 private int atk;//攻击力
 private int def;//防卫力
 
 
 public void StateDisplay(){
  System.out.println("当前角色的状态:");
  System.out.println("体力:"+vit);
  System.out.println("攻击力:"+atk);
  System.out.println("防卫力:"+def);
 }
 
 public RoleStateMemento SaveState(){
 return (new RoleStateMemento(vit,atk,def)); 
 }
 
 public void RecoveryState(RoleStateMemento memento){
  this.vit = memento.getVit();
  this.atk = memento.getAtk();
  this.def = memento.getDef();
 }
 
 public void GetInitState(){
  this.atk = 100;
  this.vit = 100;
  this.def = 100;
 }
 public void Fight() {
  
  this.atk = 0;
  this.vit = 0;
  this.def = 0;
 }
}
---------------------------------------
package liu.memento.demo;
public class RoleStateMemento {
 private int vit;//生命力
 private int atk;//攻击力
 private int def;//防卫力
 public RoleStateMemento(int vit2, int atk2, int def2) {
  this.vit = vit2;
  this.atk = atk2;
  this.def = def2;
 }
 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;
 }
 
}

---------------------------------------
package liu.memento.demo;
public class RoleStateCaretaker {
 private RoleStateMemento memento;
 public void setMemento(RoleStateMemento memento) {
  this.memento = memento;
 }
 public RoleStateMemento getMemento() {
  return memento;
 }
}

-----------------------------------------
package liu.memento.demo;
public class Main {
 /**
  * memento模式,也叫备忘录模式
  */
 public static void main(String[] args) {
  //before fight to boss
  GameRole lixiaoyao = new GameRole();
  lixiaoyao.GetInitState();
  lixiaoyao.StateDisplay();
  
  //store the game data
  RoleStateCaretaker stateAdmin = new RoleStateCaretaker();
  stateAdmin.setMemento(lixiaoyao.SaveState());
  
  //fight the boss. and all the state become zero
  lixiaoyao.Fight();
  lixiaoyao.StateDisplay();
  
  //after rescovery the state
  lixiaoyao.RecoveryState(stateAdmin.getMemento());
  lixiaoyao.StateDisplay();
 }
}

-----------------------------------------

原创粉丝点击