第十八章-备忘录模式
备忘录(Memento): 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状态。
Memento模式比较适用于功能比较复杂的,但需要维护或记录属性历史的类,或者需要保存的属性只是众多属性中的一小部分是,Originator可以根据保存的Memento信息还原到前一状态。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class RoleStateMemento
{
private:
int vit, atk, def;
public:
RoleStateMemento(int vit_t, int atk_t, int def_t)
{
vit = vit_t, atk = atk_t, def = def_t;
}
int getVit() { return vit; }
void setVit(int vit_t) { vit = vit_t; }
int getAtk() { return atk; }
void setAtk(int atk_t) { atk = atk_t; }
int getDef() { return def; }
void setDef(int def_t) { def = def_t; }
};
class GameRole
{
private:
int vit;
int atk;
int def;
public:
int getVit() { return vit; }
void setVit(int vit_t) { vit = vit_t; }
int getAtk() { return atk; }
void setAtk(int atk_t) { atk = atk_t; }
int getDef() { return def; }
void setDef(int def_t) { def = def_t; }
void StateDisplay()
{
cout << "角色当前状态:" << endl;
cout << "体力:" << vit << endl;
cout << "攻击力:" << atk << endl;
cout << "防御力:" << def << endl;
}
void GetInitState()
{
vit = 100, atk = 100, def = 100;
}
void Fight()
{
vit = 0, atk = 0, def = 0;
}
RoleStateMemento* SaveState()
{
return (new RoleStateMemento(vit, atk, def));
}
void RecoveryState(RoleStateMemento* memento)
{
vit = memento->getVit();
atk = memento->getAtk();
def = memento->getDef();
}
};
class RoleStateCaretaker
{
private:
RoleStateMemento* memento;
public:
RoleStateMemento* getMemento() { return memento; }
void setMemento(RoleStateMemento* memento_t) { memento = memento_t; }
};
int main()
{
GameRole* lixiaoyao = new GameRole();
lixiaoyao->GetInitState();
lixiaoyao->StateDisplay();
RoleStateCaretaker* stateAdmin = new RoleStateCaretaker();
stateAdmin->setMemento(lixiaoyao->SaveState());
lixiaoyao->Fight();
lixiaoyao->StateDisplay();
lixiaoyao->RecoveryState(stateAdmin->getMemento());
lixiaoyao->StateDisplay();
system("pause");
return 0;
}