美文网首页
备忘录模式

备忘录模式

作者: 钟离惜 | 来源:发表于2020-10-28 10:12 被阅读0次

备忘录模式属于状态变化模式。
在状态发生改变时,使用备忘录记录当前的状态,如果需要回滚操作,则取出先前记录的状态。
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先的状态。

使用场景
需要提供保存和恢复数据的相关状态场景。
提供一个可回滚rollback操作。
需要监控的副本场景。
数据库连接的事务管理就是备忘录模式
注意事项:
备忘录的声明期:作用在最近的代码。不使用就立即删除。
备忘录不是华佗在世,起死回生。
备忘录的性能:不能用在for中,不能用频繁建立。消耗资源太多,这会是设计重构的前兆。

示例代码

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class STMemento
{
private:
    int iVitality;
public:
    STMemento() {}
    STMemento(int iVitality)
    {
        this->iVitality = iVitality;
    }

    int GetVitality() const
    {
        return this->iVitality;
    }
};

class STOriginator
{
private:
    int iVitality;
    string name;
public:
    STOriginator(string strName, int iVit) : iVitality(iVit), name(strName)
    {

    }

    STMemento* SaveState()
    {
        return new STMemento(iVitality);
    }

    void RecoverState(const STMemento* stMemento)
    {
        this->iVitality = stMemento->GetVitality();
    }

    void SetVitality(int iVit)
    {
        this->iVitality = iVit;
    }

    void Show()
    {
        cout << "Name: " << name << endl;
        cout << "Live: " << iVitality << endl;
    }
};

class STCareTaker
{
private:
    vector<STMemento*> vecStMemento;

public:
    void AddMemento(STMemento* stMemento)
    {
        vecStMemento.push_back(stMemento);
    }

    STMemento* GetMemento(int Iindex)
    {
        if (Iindex >= vecStMemento.size())
            return NULL;
        else
            return vecStMemento[Iindex];
    }
};

int main(int argc, char* argv[])
{
    STOriginator* pstOriginator = new STOriginator("xxx", 100);
    cout << "原始状态: " << endl;
    pstOriginator->Show();

    STCareTaker* pstCareTaker = new STCareTaker();
    pstCareTaker->AddMemento(pstOriginator->SaveState());

    pstOriginator->SetVitality(50);
    cout << "战斗后状态: " << endl;
    pstOriginator->Show();

    pstOriginator->RecoverState(pstCareTaker->GetMemento(0));
    cout << "归档后状态: " << endl;
    pstOriginator->Show();

    return 0;
}

转载文章
设计模式——备忘录模式(C++实现)
设计模式--备忘录模式C++实现

相关文章

网友评论

      本文标题:备忘录模式

      本文链接:https://www.haomeiwen.com/subject/fyczmktx.html