设计模式之备忘录模式(Memento)

作用: 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将改对象恢复到原先保存的状态。

#include 
#include 

using namespace std;

//保存的信息
class Memento
{
public:
    Memento(int vit, int att, int def)
        :_vitality(vit),_attack(att),_defense(def)
    {
    }

    Memento & operator =(const Memento &memento)
    {
        _vitality = memento._vitality;
        _attack = memento._attack;
        _defense = memento._defense;
    }
public:
    int _vitality; //生命值
    int _attack;   //进攻值
    int _defense;  //防守值
};

//游戏角色
class GameRole
{
public:
    GameRole():_vitality(100),_attack(100),_defense(100){}

    Memento save()
    {
        Memento memento(_vitality,_attack,_defense);
        return memento;
    }

    void load(Memento memento)
    {
        _vitality = memento._vitality;
        _attack = memento._attack;
        _defense = memento._defense;
    }

    void show()
    {
        cout << "vitality : " << _vitality << ", attack : " << _attack
             << ", defense : "<< _defense << endl;
    }

    void attack()
    {
        _vitality -= 10;
        _attack -= 10;
        _defense -= 10;
    }

private:
    int _vitality;
    int _attack;
    int _defense;
};

//进度
class Caretake
{
public:
    Caretake(){}
    void save(Memento memento)
    {
        _VecMemento.push_back(memento);
    }

    Memento load(unsigned int state)
    {
        if(_VecMemento.size() > state)
            return _VecMemento[state];
        return Memento(100,100,100);
    }

private:
    vector _VecMemento;
};

int main()
{
    Caretake caretake;
    GameRole role;
    role.show(); //初始值
    caretake.save(role.save()); //保存状态
    role.attack();
    role.show();   //进攻后
    role.load(caretake.load(0)); //载入状态
    role.show();    //恢复状态

    return 0;
}

这里写图片描述

你可能感兴趣的:(设计模式,设计模式,备忘录)