设计模式之备忘录模式

备忘录模式原理:将对象的私有数据存储在其他地方,以便重新加载

代码如下:

#include <iostream>

#include <string>

#include <vector>

using namespace std;



class GameRole;

class Memeno

{

public:

	Memeno(int vitality = 0,int defense = 0,int attack = 0):

	m_vitality(vitality),m_defense(defense),m_attack(attack){}

	void show()

	{

		cout << "vitality:" << m_vitality << "m_defense:" <<m_defense<<"m_attack:"<<m_attack<<endl;

	}

friend GameRole;

private:

	int m_vitality;

	int m_defense;

	int m_attack;

};



class GameRole

{

public:

	GameRole():m_vitality(100),m_defense(100),m_attack(100){}

	Memeno Save()

	{

		return Memeno(m_vitality,m_defense,m_attack);

	}

	

	void Load(Memeno memeno)

	{

		m_vitality = memeno.m_vitality;

		m_defense = memeno.m_defense;

		m_attack = memeno.m_attack;

	}

	

	void attack()

	{

		m_vitality-=10;

		m_defense-=10;

		m_attack-=10;

	}



	void show()

	{

		cout << "vitality:" << m_vitality << "m_defense:" <<m_defense<<"m_attack:"<<m_attack<<endl;

	}



private:

	int m_vitality;

	int m_defense;

	int m_attack;

};



class MemnnoLibary

{

public:

	void Save(Memeno memeno)

	{

		m_vecMemeno.push_back(memeno);

	}

	Memeno Load(int state)

	{

		return m_vecMemeno[state];

	}

private:

	vector<Memeno> m_vecMemeno;



};







int main()

{

	GameRole role;

	Memeno memenno;

	MemnnoLibary ml;

	

	role.show();

	ml.Save(role.Save());

	role.attack();

	role.show();

	role.Load(ml.Load(0));

	role.show();

	return 0;

}

 

你可能感兴趣的:(备忘录模式)