设计模式学习笔记(二十一)-备忘录模式

一、概述

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

二、适用性

1.必须保存一个对象在某一个时刻的(部分)状态,这样以后需要时它才能恢复到先前的状态。 

2.如果一个用接口来让其它对象直接得到这些状态,将会暴露对象的实现细节并破坏对象的封装性。

三、参与者

1.Memento 备忘录存储原发器对象的内部状态。

2.Originator 原发器创建一个备忘录,用以记录当前时刻它的内部状态。 使用备忘录恢复内部状态. 

3.Caretaker 负责保存好备忘录。 不能对备忘录的内容进行操作或检查。

四、类图

设计模式学习笔记(二十一)-备忘录模式

五、示例

备忘录模式代码

package com.roc.meomory;
/**
 * 游戏角色
 * @author liaowp
 *
 */
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 RoleStateMemento saveMemento(){
        return (new RoleStateMemento(vit, atk));
    }
    
    public void recove(RoleStateMemento roleStateMemento){
        this.vit=roleStateMemento.getVit();
        this.atk=roleStateMemento.getAtk();
    }
}
package com.roc.meomory;
/**
 * 游戏角色管理类
 * @author liaowp
 *
 */
public class RoleStateMange {
    
    private RoleStateMemento memento;

    public RoleStateMemento getMemento() {
        return memento;
    }

    public void setMemento(RoleStateMemento memento) {
        this.memento = memento;
    }
    
}
package com.roc.meomory;
/**
 * 存储类
 * @author liaowp
 *
 */
public class RoleStateMemento {
        
    private int vit;
    private int atk;
    
    public RoleStateMemento(int vit, int atk){
        this.vit=vit;
        this.atk=atk;
    }

    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;
    }
}
package com.roc.meomory;
/**
 * 备忘录模式
 * @author liaowp
 *
 */
public class Client {
    public static void main(String[] args) {
        GameRole liaowp=new GameRole();
        liaowp.init();
        liaowp.show();
        RoleStateMange adminMange=new RoleStateMange();
        adminMange.setMemento(liaowp.saveMemento());//保存
        liaowp.fightBoss();
        liaowp.show();
        liaowp.recove(adminMange.getMemento());
        liaowp.show();
        
    }
}

备忘录模式适用场景

  适合功能比较复杂的,但需要维护或记录属性历史的功能。