Java大数据平台开发 学习笔记(51)—— java设计模式(备忘录模式)知识汇总

一、前言:

备忘录模式的注意事项和细节:

  1. 给用户提供了一个可恢复的机制,可以使用户方便的回到某个历史的状态。
  2. 实现了信息的封装,使得用户无需关心状态保存的细节。
  3. 如果类的成员变量过多,势必会占用比较大的资源,而且每次保存都会消耗一定的内存。

二、备忘录模式:

2.1、UML 图:

在这里插入图片描述

2.2、代码实例:

Step 1) 创建 Memento 类:
public class Memento {
    private int vit;
    private int def;

    public Memento(int vit, int def) {
        this.vit = vit;
        this.def = def;
    }

    public int getVit() {
        return vit;
    }

    public void setVit(int vit) {
        this.vit = vit;
    }

    public int getDef() {
        return def;
    }

    public void setDef(int def) {
        this.def = def;
    }
}

Step 2) 创建 Caretaker 类:
public class Caretaker {
    private Memento memento;
    private ArrayList<Memento> mementos;
    private HashMap<String, ArrayList<Memento>> rolesMementos;

    public Memento getMemento(){
        return memento;
    }

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

Step 3) 创建 GameRole 类:
public class GameRole {
    private int vit;
    private int def;

    public int getVit() {
        return vit;
    }

    public void setVit(int vit) {
        this.vit = vit;
    }

    public int getDef() {
        return def;
    }

    public void setDef(int def) {
        this.def = def;
    }

    public Memento creatMenento(){
        return new Memento(vit, def);
    }

    public void revoverGameRoleFromMementto(Memento memento){
        this.vit = memento.getVit();
        this.def = memento.getDef();
    }

    public void dispalay(){
        System.out.println("游戏当前的攻击力:"+ this.vit + " 防御力:" + this.def);
    }

}


Step 4) 创建 main 方法:
public class Client {
    public static void main(String[] args) {
        GameRole gameRole = new GameRole();
        gameRole.setVit(100);
        gameRole.setDef(100);

        System.out.println("===== BOSS 大战前的状态 =====");
        gameRole.dispalay();

        Caretaker caretaker = new Caretaker();
        caretaker.setMemento(gameRole.creatMenento());

        System.out.println("===== BOSS 大战前后状态 =====");
        gameRole.setVit(30);
        gameRole.setDef(30);
        gameRole.dispalay();

        System.out.println("===== BOSS 大战后,使用备忘录恢复后的状态 =====");
        gameRole.revoverGameRoleFromMementto(caretaker.getMemento());
        gameRole.dispalay();
    }
}


• 由 ChiKong_Tam 写于 2020 年 10 月 22 日

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值