备忘录模式

来源:互联网 发布:歼31是不是下马了知乎 编辑:程序博客网 时间:2024/06/02 06:50

定义:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态。

类图:

这里写图片描述

发起人(游戏角色)

public class GameRole {    private int vit;    private int atk;    private int def;    public void stateDisplay() {        System.out.println("当前角色状态:");        System.out.println("生命值:" + this.vit);        System.out.println("攻击力:" + this.atk);        System.out.println("防御力:" + this.def);    }    //保存当前状态    public RoleStateMemento saveSate() {        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.vit = 100;        this.atk = 100;        this.def = 100;    }    public void Fight() {        this.vit = 0;        this.atk = 0;        this.def = 0;    }    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 int getVit() {        return vit;    }    public void setVit(int vit) {        this.vit = vit;    }}

备忘录,保存对象状态

public class RoleStateMemento {    private int vit;    private int atk;    private int def;    public RoleStateMemento(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 RoleStateCaretaker {    //持有备忘录引用    private RoleStateMemento roleStateMemento;    public RoleStateMemento getRoleStateMemento() {        return roleStateMemento;    }    public void setRoleStateMemento(RoleStateMemento roleStateMemento) {        this.roleStateMemento = roleStateMemento;    }}

客户端

public class Main {    public static void main(String[] args) {        GameRole gameRole = new GameRole();        gameRole.getInitState();        gameRole.stateDisplay();        RoleStateCaretaker stateCaretaker = new RoleStateCaretaker();        stateCaretaker.setRoleStateMemento(gameRole.saveSate());        gameRole.Fight();        gameRole.stateDisplay();        gameRole.recoveryState(stateCaretaker.getRoleStateMemento());        gameRole.stateDisplay();    }}

这里写图片描述