设计模式之备忘录模式

设计模式 Java About 1,463 words

作用

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

为了节约内存,备忘录模式可以和原型模式配合使用。

原理

memento.png

Originator:需要保存状态的对象。

Memento:备忘录对象,负责保存记录,即Originator的内部状态。

Caretaker:守护者对象,负责保存多个备忘录对象,使用集合管理,提高效率。

案例

Originator

public class GameRole {

    public int vit;
    public int def;

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

    public void recoverGameRoleFromMemento(Memento memento) {
        this.vit = memento.vit;
        this.def = memento.def;
    }

    public void display() {
        System.out.println("GameRole: " + vit + " --- " + def);
    }

}

Memento

public class Memento {

    public int vit;
    public int def;

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

Caretaker

public class Caretaker {
    private Memento memento;

    public Memento getMemento() {
        return memento;
    }

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

调用

public class Client {
    public static void main(String[] args) {
        GameRole gameRole = new GameRole();
        gameRole.vit = 100;
        gameRole.def = 100;
        gameRole.display();

        Caretaker caretaker = new Caretaker();
        caretaker.setMemento(gameRole.createMemento());
        gameRole.vit = 30;
        gameRole.def = 30;
        gameRole.display();

        gameRole.recoverGameRoleFromMemento(caretaker.getMemento());
        gameRole.display();
    }
}
Views: 2,437 · Posted: 2019-12-31

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh