(十三)备忘录模式

1. 定义

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

  • Originator(发起人),负责创建一个备忘录(Memento),用以记录当前时刻它的内部状态,并可使用备忘录恢复内部状态。Originator可根据需要决定Memento存储Originator的哪些内部状态;
  • Memento(备忘录),负责存储Originator对象的内部状态,并可防止Originator以外的其他对象访问备忘录Memento;
  • Caretaker(管理者),负责保存好备忘录(Memento),不能对备忘录的内容进行操作或查看;

2. 示例

#include <iostream>
#include <string>

struct State
{
    std::string m_switch;
    std::string m_other;
};

class Memento
{
public:
    Memento(State s) :m_state(s){}
    State GetState(){ return m_state; }
private:
    State m_state;
};

class Originator
{
public:
    Memento* CreateMemento(){
        return new Memento(m_state);
    }
    void Recovery(Memento *m){
        m_state = m->GetState();
    }

    void SetState(const State &s){
        m_state = s;
    }
    void Show(){
        std::cout << "state is " << m_state.m_switch << std::endl;
    }
private:
    State m_state;
};

class Caretaker
{
public:
    void SetMemento(Memento *m){
        m_memento = m;
    }
    Memento* GetMemento(){
        return m_memento;
    }
private:
    Memento *m_memento;
};


void Client()
{
    Originator* o = new Originator();
    o->SetState(State{ "on", "" });
    o->Show();

    Memento* m = o->CreateMemento();
    Caretaker c;
    c.SetMemento(m);

    o->SetState(State{ "off", "" });
    o->Show();

    o->Recovery(c.GetMemento());
    o->Show();

    delete o;
    delete m;
}

int main()
{
    Client();
    return 0;
}

3. 总结

备忘录模式最常见的是用于游戏存档。

posted @ 2018-08-30 08:05  yvhqbat  阅读(125)  评论(0编辑  收藏  举报