1.备忘录模式简介
备忘录模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在对象之外保存这个状态,这样以后就可以将对象恢复到原先保存的状态。UML类图如下:
Originator将内部状态保存到Memento中,memento通过caretaker进行管理。
2.备忘录实现
将游戏打boss前的状态保存下来,战斗结果不理想时进行恢复。UML类图如下:
c 代码实现如下:
代码语言:javascript复制#include<exception>
#include <iostream>
#include<string>
using namespace std;
//9.备忘录模式:打游戏进度保存
class PlayerMemonto
{
public:
PlayerMemonto(int ilife=0, int iattack=0, int idef=0) :m_life(ilife), m_attack(iattack), m_def(idef){};
int getLife(){ return m_life; }
int getAttack(){ return m_attack; }
int getDef(){ return m_def; }
private:
int m_life;
int m_attack;
int m_def;
};
class GamePlayer
{
public:
GamePlayer():m_life(100),m_attack(100),m_def(100){}
PlayerMemonto createMemonto()
{
return PlayerMemonto(m_life, m_attack, m_def);
}
void recover(PlayerMemonto iMemonto)
{
m_life = iMemonto.getLife();
m_attack = iMemonto.getAttack();
m_def = iMemonto.getDef();
}
void fight()
{
m_life = 13;
m_attack = 23;
m_def = 9;
}
void show()
{
cout << "life:" << m_life << " attack:" << m_attack << " def:" << m_def << endl;
}
private:
int m_life;
int m_attack;
int m_def;
};
class PlayerMemontoManeger
{
public:
void setMemonto(PlayerMemonto iMemonto)
{
m_memonto = iMemonto;
}
PlayerMemonto getMemonto(){ return m_memonto; }
private:
PlayerMemonto m_memonto;
};
int main()
{
GamePlayer player;
player.show();
PlayerMemonto memonto = player.createMemonto();
PlayerMemontoManeger maneger;
maneger.setMemonto(memonto);
player.fight();
player.show();
player.recover(maneger.getMemonto());
player.show();
system("pause");
}
3.总结
不知道为啥还需要一个管理者类,留给以后的自己思考吧。