定义:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后可将该状态恢复到原先保存的状态。
适用于功能比较复杂,但需要维护或记录属性历史的类,或者需要保存的属性只是属性中的一小部分时,可以根据保存的属性信息还原到前一状态。
代码:
//备忘录模式
#include <iostream>
#include <string>
using namespace std;
class RoleStateMemento;
class GameRole
{
public:
int getVit()
{
return vit;
}
void setVit(int value)
{
vit = value;
}
int getAtk()
{
return atk;
}
void setAtk(int value)
{
atk = value;
}
int getDef()
{
return def;
}
void setDef(int value)
{
def = value;
}
void GetInitState()
{
this->vit = 100;
this->atk = 100;
this->def = 100;
}
//战斗
void Fight()
{
this->vit = 0;
this->atk = 0;
this->def = 0;
}
//保存角色状态
RoleStateMemento* SaveState();
//恢复角色状态
void RecoveryState(RoleStateMemento* memento);
void StateDisplay()
{
cout << "角色当前状态:";
cout << "体力:"<< vit;
cout << "攻击力:" << atk;
cout << "防御力:" << def << endl;
}
private:
int vit;
int atk;
int def;
};
class RoleStateMemento
{
public:
RoleStateMemento(int vit,int atk,int def)
{
this->atk = atk;
this->def = def;
this->vit = vit;
}
int getVit()
{
return vit;
}
void setVit(int value)
{
vit = value;
}
int getAtk()
{
return atk;
}
void setAtk(int value)
{
atk = value;
}
int getDef()
{
return def;
}
void setDef(int value)
{
def = value;
}
private:
int vit;
int atk;
int def;
};
class RoleStateCaretaker
{
public:
RoleStateMemento* getMemento()
{
return memento;
}
void setMemento(RoleStateMemento* value)
{
memento = value;
}
private:
RoleStateMemento* memento;
};
RoleStateMemento* GameRole::SaveState()
{
return (new RoleStateMemento(vit,atk,def));
}
//恢复角色状态
void GameRole::RecoveryState(RoleStateMemento* memento)
{
this->vit = memento->getVit();
this->atk = memento->getAtk();
this->def = memento->getDef();
}
int main()
{
//大战Boss前
GameRole* lixiaoyao = new GameRole();
lixiaoyao->GetInitState();
lixiaoyao->StateDisplay();
//保存进度
RoleStateCaretaker* backup = new RoleStateCaretaker();
backup->setMemento(lixiaoyao->SaveState());
//大战Boss时,损耗严重
lixiaoyao->Fight();
lixiaoyao->StateDisplay();
//恢复之前状态
lixiaoyao->RecoveryState(backup->getMemento());
lixiaoyao->StateDisplay();
return 0;
}