现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

代码版设计模式21:备忘录模式【行为型】

2013-03-10 12:26 工业·编程 ⁄ 共 1362字 ⁄ 字号 暂无评论

#include <iostream>
#include <vector>
using namespace std;

//
class CMemento
{
public:
    CMemento(int vitality, int attack, int defense) : m_vitality(vitality), m_attack(attack), m_defense(defense) { }
    CMemento& operator=(const CMemento& memento)
    {
        m_vitality = memento.m_vitality;
        m_attack = memento.m_attack;
        m_defense = memento.m_defense;
        return *this;
    }

public:
    int m_vitality;
    int m_attack;
    int m_defense;
};

class CGameRole
{
public:
    CGameRole() : m_vitality(100), m_attack(100), m_defense(100) { }

    CMemento Save()
    {
        CMemento memento(m_vitality, m_attack, m_defense);
        return memento;
    }

    void Load(const CMemento memento)
    {
        m_vitality = memento.m_vitality;
        m_attack = memento.m_attack;
        m_defense = memento.m_defense;
    }

    void Show() { cout<<"vitality:"<<m_vitality<<" attack:"<<m_attack<<" defense:"<<m_defense<<endl; }

    void Attack()
    {
        m_vitality -= 10;
        m_attack -= 10;
        m_defense -= 10;
    }

private:
    int m_vitality;
    int m_attack;
    int m_defense;
};

class CCareTake
{
public:
    void Save(CMemento memento) { m_mementoVec.push_back(memento); }
    CMemento Load(int state) { return m_mementoVec[state]; }

private:
    vector<CMemento> m_mementoVec;
};

//
void main()
{
    CGameRole gameRole;
    gameRole.Show();

    CCareTake caretake;
    caretake.Save(gameRole.Save());

    gameRole.Attack();
    gameRole.Show();

    gameRole.Load(caretake.Load(0));
    gameRole.Show();
}

给我留言

留言无头像?