【定义】备忘录(Memento),在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
【场景】备忘录模式,当然是在单机游戏里面用的多。比如角色扮演的《仙剑奇侠传》,在打Boss之前我们都会先保存当前进度,以便Boss没死,自己死了,好回到之前的存档点继续。
【UML】
【代码】
#include <iostream>
using namespace std;
//备忘录
class Memento
{
private:
int vitality; //生命值
int attack; //攻击值
int defence; //防御值
public:
Memento():vitality(0), attack(0), defence(0){}
Memento(int v, int a, int d):vitality(v), attack(a), defence(d){}
int get_vitality()
{
return vitality;
}
void set_vitality(int v)
{
vitality = v;
}
int get_attack()
{
return attack;
}
void set_attack(int a)
{
attack = a;
}
int get_defence()
{
return defence;
}
void set_defence(int d)
{
defence = d;
}
};
//游戏角色
class Originator
{
private:
int vitality;
int attack;
int defence;
public:
Originator():vitality(100),attack(100),defence(100){}
Memento* save_state()
{
Memento* m = new Memento(vitality, attack, defence);
return m;
}
void recovery_state(Memento* m)
{
vitality = m->get_vitality();
attack = m->get_attack();
defence = m->get_defence();
}
void dead()
{
vitality = 0;
attack = 0;
defence = 0;
}
void show()
{
cout<<"vitality: "<<vitality<<endl;
cout<<"attack: "<<attack<<endl;
cout<<"defence: "<<defence<<endl;
}
};
//状态存储箱
class Caretaker
{
private:
Memento* memento;
public:
~Caretaker()
{
free(memento);
}
void set_memento(Memento* m)
{
memento = m;
}
Memento* get_memento()
{
return memento;
}
};
int main()
{
Originator* originator = new Originator;
Caretaker* caretaker = new Caretaker;
cout<<"战斗前:"<<endl;
originator->show();
caretaker->set_memento(originator->save_state());
cout<<endl;
cout<<"战斗后:"<<endl;
originator->dead();
originator->show();
cout<<endl;
cout<<"恢复存档:"<<endl;
originator->recovery_state(caretaker->get_memento());
originator->show();
delete caretaker;
delete originator;
return 0;
}