首页 > 代码库 > 备忘录模式之C++实现

备忘录模式之C++实现

 

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class Info
{
private:
    string name;
    int health;
    int attack;
    int defend;
public:
    Info(string name)
    {
        this->name = name;
        this->health = 0;
        this->attack = 0;
        this->defend = 0;
    }

    Info(string name, int health, int attack, int defend)
    {
        this->name   = name;
        this->health = health;
        this->attack = attack;
        this->defend = defend;
    }

    string GetName()
    {
        return this->name;
    }

    int GetHealth()
    {
        return this->health;
    }

    int GetAttack()
    {
        return this->attack;
    }

    int GetDefend()
    {
        return this->defend;
    }

    void Set(string name, int health, int attack, int defend)
    {
        this->name   = name;
        this->health = health;
        this->attack = attack;
        this->defend = defend;
    }

    void Set(Info *info)
    {
        this->name   = info->GetName();
        this->health = info->GetHealth();
        this->attack = info->GetAttack();
        this->defend = info->GetDefend();
    }

    void Show()
    {
        cout << "================== Info ==================" << endl;
        cout << "name: " << this->name << endl;
        cout << "health: " << this->health << endl;
        cout << "attack: " << this->attack << endl;
        cout << "defend: " << this->defend << endl;
    }
};

class Memento
{
private:
    Info *info;
public:
    Memento(Info *info)
    {
        this->info = new Info("");
        this->info->Set(info);
    }

    void SetInfo(Info *info)
    {
        this->info = info;
    }

    Info* GetInfo()
    {
        return info;
    }
};

class Originator
{
private:
    Info *info;
public:
    Originator()
    {
        info = new Info("");
    }
    
    Memento* CreateMemento()
    {
        return new Memento(info);
    }

    void RestoreMemento(Memento* memento)
    {
        this->info->Set(memento->GetInfo());
    }

    void SetInfo(string name, int health, int attack, int defend)
    {
         this->info->Set(name, health, attack, defend);
    }

    Info* GetInfo()
    {
        return info;
    }
};

class CareTaker
{
private:
    Memento *memento;
public:
    Memento* LoadMemento()
    {
        return memento;
    }
    void SaveMemento(Memento *memento)
    {
        this->memento = memento;
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    CareTaker   *pCareTaker  = new CareTaker;
    Originator  *pOriginator = new Originator;

    //设置信息
    pOriginator->SetInfo("战士"1000100100);
    pOriginator->GetInfo()->Show();

    //创建备忘录对象,储存信息
    pCareTaker->SaveMemento(pOriginator->CreateMemento());

    //信息发生变化
    pOriginator->SetInfo("战士"0100100);
    pOriginator->GetInfo()->Show();

    //恢复备份数据
    pOriginator->RestoreMemento(pCareTaker->LoadMemento());
    pOriginator->GetInfo()->Show();

    return 0;
}