现在的位置: 首页 > 综合 > 正文

备忘录模式

2014年01月18日 ⁄ 综合 ⁄ 共 2065字 ⁄ 字号 评论关闭

最近在看大话设计模式,今天看了备忘录模式,由此而写的。

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

其主要有三个类:

Originator:发起人,负责创建一个备忘录Memento,用来记录当前时刻的内部状态,并可使用备忘录恢复内部状态

Memento:备忘录,负责存储Originator对象的内部状态,并防止Originator以外的其他对象访问备忘录Memento

Cartaker:管理者,负责保存好备忘录Memento,不能对备忘录的内容进行操作或检查

eg:

备忘录:

public class RoleMemento {
    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 RoleMemento(int vit, int atk, int def) {
        this.vit = vit;
        this.atk = atk;
        this.def = def;
    }
}

发起人:

public class OrgRole {
    private int vit, atk, def;

    public RoleMemento SaveState() {
        return new RoleMemento(vit, atk, def);
    }
    
    public void RecoveryState(RoleMemento memento) {
        this.vit = memento.getVit();
        this.atk = memento.getAtk();
        this.def = memento.getDef();
    }
    
    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.atk = 100;
        this.vit = 100;
        this.def = 100;
    }
    
    public void Fight() {
        this.atk = 0;
        this.vit = 0;
        this.def = 0;
    }
}

管理者:

public class RoleStateCaretaker {
    private RoleMemento memento;

    public RoleMemento getMemento() {
        return memento;
    }

    public void setMemento(RoleMemento memento) {
        this.memento = memento;
    }
    
    public static void main(String[] args) {
        OrgRole gewei = new OrgRole();
        gewei.GetInitState();
        gewei.StateDisplay();
        
        RoleStateCaretaker back = new RoleStateCaretaker();
        back.setMemento(gewei.SaveState());
        
        gewei.Fight();
        gewei.StateDisplay();
        
        gewei.RecoveryState(back.getMemento());
        gewei.StateDisplay();
    }
}

自己写了代码后发现,其实备忘录模式就是通过备忘录类存储状态数据,管理类来存取中间备忘录,发起人用于存放和操作当前状态数据;

虽然实现了数据的存储恢复功能,但缺点是在备忘录中状态数据过多,将造成很大的内存消耗。

抱歉!评论已关闭.