備忘錄模式
備忘錄模式UML
備忘錄模式是在不破壞封閉的前提下,捕獲一個對象的内部狀态,并在該對象之外儲存這個狀态。這樣以後就可将該對象恢複到原先儲存的狀态。
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <Windows.h>
using namespace std;
//備份資料
class SaveDate
{
public:
SaveDate(int attack, int defense, int hp)
{
this->attack = attack;
this->defense = defense;
this->hp = hp;
}
int getAttack() const { return attack; }
int getDefense() const { return defense; }
int getHp() const { return hp; }
private:
int attack; //攻擊力
int defense;//防禦力
int hp; //生命力
};
//遊戲角色資料
class Person
{
public:
Person():attack(0), defense(0), hp(0){}
SaveDate* createSaveDate()
{
return new SaveDate(attack, defense, hp);
}
void setSaveDate(const SaveDate* date)
{
attack = date->getAttack();
defense = date->getDefense();
hp = date->getHp();
}
void showPerson()
{
cout << "英雄攻擊力" << attack << endl;
cout << "英雄防禦力" << defense << endl;
cout << "英雄生命力" << hp << endl;
}
void deductVal(int attackVal, int defenseVal, int hpVal)
{
//增減人物數值
attack += attackVal;
defense += defenseVal;
hp += hpVal;
}
private:
int attack; //攻擊力
int defense;//防禦力
int hp; //生命力
};
//備忘錄管理類
class SaveDateMgr
{
private:
SaveDate* save;
public:
SaveDate* restoreSaveDate()
{
return save;
}
void addSaveDate2Mgr(SaveDate* save)
{
this->save = save;
}
};
int main()
{
Person hero;
SaveDateMgr mgr;
//裝備武器,提升三維
hero.deductVal(10, 5, 100);
hero.showPerson();
//儲存存檔
mgr.addSaveDate2Mgr(hero.createSaveDate());
//遇到怪獸進行戰鬥,掉80血
hero.deductVal(0, 0, -80);
hero.showPerson();
//恢複存檔
hero.setSaveDate(mgr.restoreSaveDate());
hero.showPerson();
system("pause");
return 1;
}