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 日

猜你喜欢

转载自blog.csdn.net/qq_42209354/article/details/109229850
今日推荐