c++ 备忘录模式(memento)

备忘录模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态[DP]。举个简单的例子,我们玩游戏时都会保存进度,所保存的进度以文件的形式存在。这样下次就可以继续,而不用从头开始。这里的进度其实就是游戏的内部状态,而这里的文件相当于是在游戏之外保存状态。这样,下次就可以从文件中读入保存的进度,从而恢复到原来的状态。这就是备忘录模式。

        给出备忘录模式的UML图,以保存游戏的存档为例。

 

代码如下:

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

using namespace std;

class Memento
{
public:
    int m_score;                 //分数
    int m_grade;             //等级
    string m_equipment ; //装备
public:
    Memento(int score,int grade,string equipment):m_score(score),m_grade(grade),m_equipment(equipment)
    {
    
    }
    Memento& operator=(const Memento &memento)
    {
        m_score = memento.m_score;
        m_grade = memento.m_grade;
        m_equipment = memento.m_equipment;
        return *this;
    }
};

class GamePlayer
{
public:
    GamePlayer():m_score(0),m_grade(0),m_equipment("无装备")
    {
        
    }
    void load(Memento memento)
    {
        m_score = memento.m_score;
        m_grade = memento.m_grade;
        m_equipment = memento.m_equipment;
    }
    Memento  save()
    {
        Memento memento(m_score,m_grade,m_equipment);
        return memento;
    }
    void show()
    {
        cout << "score: " <<m_score <<endl;
        cout << "grade: " <<m_grade <<endl;
        cout << "equipment :" <<m_equipment <<endl;
     }
private:
    int m_score;                 //分数
    int m_grade;                 //等级
    string m_equipment ; //装备

};

class Archive
{
public:
    Archive()
    {

    }
    void addItem(Memento memento)
    {
        m_mementArray.push_back(memento);
    }
    Memento Load(int state) 
    {
        return m_mementArray[state];
    }
private:
    std::vector<Memento> m_mementArray;
};

主函数:

#include "memento.h"

int main()
{
    Archive archive;
    GamePlayer player;   
    player.show();            //玩家初始化装备 

    Memento memento(100,45,"青龙偃月刀");  //玩家装备记录
    player.load(memento);
    player.show();
    archive.addItem(memento);   //存档游戏
    system("pause");
    return 0;
}

 

posted @ 2013-12-27 14:55  onlycxue  阅读(1103)  评论(0编辑  收藏  举报