1. 程式人生 > >Design Patterns 18: Memento

Design Patterns 18: Memento

在不違反封裝原則的前提下,捕獲記錄物件的內部狀態,使得物件具備復原的能力。

struct Memento
{
    int GetState() { return _state; };
    void SetState(Memento* m) { _state = m->GetState(); };

    Memento(int state) : _state(state) {}
private:
    int _state;
};

struct Originator
{
    void SetMemento(Memento* m)
    {
        _state = m->GetState();
    }

    Memento* CreateMemento()
    {
        return new Memento(_state);
    }

    Originator(int state) : _state(state) {}
private:
    int _state;
};

int main()
{
    Originator originator(10);

    auto memento = originator.CreateMemento();

    originator.SetMemento(memento);
}