C++设计模式浅识备忘录模式

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

模式实现:

struct State{
    wchar_t wcsState[260];
};

class Memento{
public:
    Memento(State *pState): m_pState(pState) {}
    State *GetState() { return m_pState; }

private:
    friend class Originator;

    State *m_pState;
};

class Originator{
public:
    Originator() : m_pState(NULL) {}
    ~Originator(){
        //Delete the storage of the state
        if(m_pState){
            delete m_pState;
            m_pState = NULL;
        }
    }

    void SetMemento(Memento *pMemento);

    Memento * CreateMemento();

    void SetValue(wchar_t *val){
        memset(wcsValue, 0, 260 * sizeof(wchar_t));
        wcscpy_s(wcsValue, 260, val);
    }

    void PrintState() { std::wcout << wcsValue << std::endl; } 

private:
    State *m_pState; //To store the object's state
    wchar_t wcsValue[260]; //This is the object's real data
};

Memento *Originator::CreateMemento(){
    m_pState = new State;
    if(m_pState == NULL)
        return NULL;
    Memento *pMemento = new Memento(m_pState);

    wcscpy_s(m_pState->wcsState, 260, wcsValue);  //Backup the value

    return pMemento;
}

void Originator::SetMemento(Memento *pMemento){
    m_pState = pMemento->GetState();
    //Recovery the data
    memset(wcsValue, 0, 260 * sizeof(wchar_t));
    wcscpy_s(wcsValue, 260, m_pState->wcsState);
}

//Manager the Memento
class Caretaker{
public:
    Memento *GetMemento() { return m_pMemento; }
    void SetMemento(Memento *pMemento){
        //Free the previous Memento
        if(m_pMemento){
            delete m_pMemento;
            m_pMemento = NULL;
        }

        //set the new Memento
        m_pMemento = pMemento;
    }
private:
    Memento *m_pMemento;
};

客户端:

int main(){ 
    Originator *pOriginator = new Originator();
    pOriginator->SetValue(L"on");
    pOriginator->PrintState();  //OutPut: on

    //Now I backup the state
    Caretaker *pCaretaker = new Caretaker();
    pCaretaker->SetMemento(pOriginator->CreateMemento());

    //Set the new state
    pOriginator->SetValue(L"off");
    pOriginator->PrintState(); //OutPut: off

    //Recovery to the old state
    pOriginator->SetMemento(pCaretaker->GetMemento());
    pOriginator->PrintState(); //OutPut: on

    if(pCaretaker)
        delete pCaretaker;
    if(pOriginator);
        delete pOriginator;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值