备忘录模式

来源:互联网 发布:thinkphp商城源码 编辑:程序博客网 时间:2024/06/03 17:38

备忘录模式介绍
备忘录模式是一种行为模式,该模式用于保存对象当前的状态,并且在之后可以再次恢复到此状态,这有点像我们平时说的‘后悔药’。备忘录模式实现的方式需要保证被保存的对象状态不能被对象从外部访问,目的是为了保护好被保存的这些对象状态的完整性以及内部实现不向外暴露。
备忘录模式的定义
在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样,以后就可以将该对象恢复到原先保存状态。
备忘录模式的使用场景
1.需要保存一个对象在某一个时刻的状态或部分状态
2.如果用一个接口来让其他对象得到这些状态,将会暴露对像的实现细节并破坏对象的封装性,一个对象不希望外界访问其他内部状态,通过中间对象可以间接访问其内部状态。
备忘录模式的UML类图
这里写图片描述
备忘录代码示例:

/***游戏角色类*/public class GameRole {    private int vit;    private int atk;    public void init(){        vit = 100;        atk = 100;    }    public void show(){        System.out.println("体力:" + vit);        System.out.println("攻击力:" + atk);    }    public void fightBoss() {        this.vit = 0;        this.atk = 0;    }    public RoleStateMenento saveMemento(){        return (new RoleStateMenento(vit,atk));    }    public void recove(RoleStateMenento roleStateMenento){        this.vit = roleStateMenento.getVit();        this.atk = roleStateMenento.getAtk();    }}
/** * 游戏角色管理类 */public class RoleStateManage {    private RoleStateMenento menento;    public RoleStateMenento getMemento(){        return menento;    }    public void setMemento(RoleStateMenento menento){        this.menento = menento;    }}
/** * 存储类 */public class RoleStateMenento {    private int vit;    private int atk;    public RoleStateMenento(int vit,int atk){        this.atk = atk;        this.vit = vit;    }    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 class Client {    public static void main(String[] args) {        GameRole role = new GameRole();        role.init();        role.show();        RoleStateManage manage = new RoleStateManage();        manage.setMemento(role.saveMemento());        role.fightBoss();        role.show();        //恢复fightBoss()之前的状态。        role.recove(manage.getMemento());        role.show();    }}

体力:100
攻击力:100
体力:0
攻击力:0
体力:100
攻击力:100

总结
备忘录模式是在不破坏封装的条件下,通过备忘录存储另外一个对象内部状态的快照,在将来合适的时候把这个对象还原到存储起来的状态。

优点

  • 给用户提供一中可以恢复状态的机制,可以使用户能够比较方便地回到某个历史的状态

  • 实现了信息的封装,使用户不需要关系状态的保存细节

缺点

  • 消耗资源,如果类的成员变量多,势必会占用比较大的资源,而且每一次保存都会消耗一定的内存。
原创粉丝点击