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

黄舟
发布: 2017-01-17 13:30:56
原创
1247人浏览过

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

模式实现:

[code]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;
};
登录后复制

客户端:

[code]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;
}
登录后复制

以上就是C++设计模式浅识备忘录模式的内容,更多相关内容请关注PHP中文网(www.php.cn)!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号