备忘录模式(Memento)_java实现

//20210122
写在前面:刚期末考试完,考了面向对象,里边儿有23个设计模式,我寻思着考完挨个儿实现一下,本文实现备忘录模式

备忘录模式核心思想

  • 类似游戏存档,将对象前一个时间点的状态保存下来,以便出现情况进行回滚和撤销操作
  • 缺点:浪费资源
  • 优点:保证系统安全,出现突发情况可以减少数据丢失

程序源代码

//游戏角色类
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("体力:"+this.vit);
        System.out.println("攻击力:"+this.atk);
        System.out.println("防御力:"+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 memento){
        this.vit = memento.getVit();
        this.atk = memento.getAtk();
        this.def = memento.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;
    }
}

//测试主类
public class Main {
    public static void main(String[] args) {
        //描述了一个打boss失败,读档的故事
        GameRole gameRole = new GameRole();
        gameRole.getInitState();
        gameRole.stateDisplay();

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

        //打boss失败-这里简化了操作直接让所有读数归零了,毕竟不是真实创建游戏系统
        gameRole.fight();
        gameRole.stateDisplay();

        //恢复状态
        gameRole.recoveryState(roleStateCaretaker.getMemento());
        gameRole.stateDisplay();
    }
}

  • 输出如下:

以上
希望对大家有所帮助

posted @ 2021-01-22 10:41  醉生梦死_0423  阅读(107)  评论(0编辑  收藏  举报