美文网首页
备忘录模式(Memento)

备忘录模式(Memento)

作者: bobcorbett | 来源:发表于2017-08-15 17:24 被阅读0次

备忘录模式(Memento):在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后可以将该对象恢复到原先保存的状态。
PS:其实就是复制了当前实体类创建了另外一个名称不一样的javabean,然后把数据拷贝过去,消耗内存做备份。

主方法

public class main {
    public static void main(String[] args) {
        GameRole gameRole = new GameRole();
        gameRole.getInitState();
        gameRole.StateDisplay();

        //保存进度
        RoleStateCaretaker stateCaretaker = new RoleStateCaretaker();
        stateCaretaker.setMemento(gameRole.saveState());

        //数据丢失
        gameRole.fight();
        gameRole.StateDisplay();

        //启用备忘录
        gameRole.recoveryState(stateCaretaker.getMemento());
        gameRole.StateDisplay();
    }
}

主实体类

public class GameRole {
    private int vit;
    private int atk;
    private int 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 void StateDisplay() {
        System.out.println("角色当前状态");
        System.out.println(String.format("体力:{%d}", this.vit));
        System.out.println(String.format("攻击力:{%d}", this.atk));
        System.out.println(String.format("防御力:{%d}", this.def));
        System.out.println("");
    }

    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 RoleStateMemento saveState() {
        return new RoleStateMemento(vit, atk, def);
    }

    public void recoveryState(RoleStateMemento roleStateMemento) {
        this.vit = roleStateMemento.getVit();
        this.atk = roleStateMemento.getAtk();
        this.def = roleStateMemento.getDef();
    }
}

备忘录实体

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 memento;

    public RoleStateMemento getMemento() {
        return memento;
    }

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

相关文章

网友评论

      本文标题:备忘录模式(Memento)

      本文链接:https://www.haomeiwen.com/subject/elevrxtx.html