设计模式之备忘录模式

【定义】备忘录(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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值