`

大话设计模式十八:备忘录模式(如果再回到从前)

 
阅读更多

备忘录模式就是把保存的细节封装在Memento中。

应用场景:Memento模式比较适用于需要维护或记录属性历史的类。

主要缺点:角色状态需要完整的存储到备忘录对象中,如果状态数据很大很多,将会非常的消耗资源。

public class GameRole {

  private String name;
  private int vitality; // 生命力
  private int attrack;  // 攻击力
  private int defence;  // 防御力

  public GameRole(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getVitality() {
    return vitality;
  }

  public void setVitality(int vitality) {
    this.vitality = vitality;
  }

  public int getAttrack() {
    return attrack;
  }

  public void setAttrack(int attrack) {
    this.attrack = attrack;
  }

  public int getDefence() {
    return defence;
  }

  public void setDefence(int defence) {
    this.defence = defence;
  }

  // 初始状态
  public void init() {
    this.vitality = 100;
    this.attrack = 50;
    this.defence = 30;
  }
  
  // 与boss大战后状态
  public void Fight() {
    this.vitality = 0;
    this.attrack = 0;
    this.defence = 0;
  }
  
  public void show(){
    System.out.println("Name: "+name);
    System.out.println("Vitality: "+this.vitality);
    System.out.println("Attrack: "+this.attrack);
    System.out.println("Defence: "+this.defence);
  }
  
  public Memento createMemento(){
    return new Memento(this.vitality,this.attrack,this.defence);
  }
  
  public void backupFromMemento(Memento m){
    this.vitality = m.getVitality();
    this.attrack = m.getAttrack();
    this.defence = m.getDefence();
  }
}

public class CareTaker {

  private Memento memento;

  public Memento getMemento() {
    return memento;
  }

  public void setMemento(Memento memento) {
    this.memento = memento;
  }
}

public class Memento {
  private int vitality;
  private int attrack;
  private int defence;

  public int getVitality() {
    return vitality;
  }

  public int getAttrack() {
    return attrack;
  }

  public int getDefence() {
    return defence;
  }

  public Memento() {
  }

  public Memento(int vit, int attrack, int defence) {
    this.vitality = vit;
    this.attrack = attrack;
    this.defence = defence;
  }
}


public class MomentoMain {
  public static void main(String[] args) {
    GameRole mario = new GameRole("Mario");
    mario.init();
    mario.show();
    
    CareTaker ct = new CareTaker();
    ct.setMemento(mario.createMemento());
    
    mario.Fight();
    mario.show();
    
    mario.backupFromMemento(ct.getMemento());
    mario.show();
  }
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics