行为型模式之备忘录模式

#include<iostream>
#include<string>
using namespace std;

class MemTo
{
public:
	MemTo(string name, int age)
	{
		m_name = name;
		m_age = age;
	}

	string getName()
	{
		return m_name;
	}

	int getAge()
	{
		return m_age;
	}

	void setName(string name)
	{
		m_name = name;
	}

	void setAge(int age)
	{
		m_age = age;
	}


private:
	string m_name;
	int m_age;
};

class Person
{
public:
	Person(string name, int age)
	{
		m_name = name;
		m_age = age;
	}

	string getName()
	{
		return m_name;
	}

	int getAge()
	{
		return m_age;
	}

	void setName(string name)
	{
		m_name = name;
	}

	void setAge(int age)
	{
		m_age = age;
	}

	MemTo *CreatMemTo()
	{
		return new MemTo(m_name, m_age);
	}

	void setMemTo(MemTo*memto)
	{
		m_name = memto->getName();
		m_age = memto->getAge();
	}

	void printT()
	{
		cout << "m_name:" << m_name << " m_age:" << m_age << endl;
	}

private:
	string m_name;
	int m_age;
	MemTo *memto;
};


//备忘录管理器
class careTaker
{
public:
	careTaker(MemTo*memto)
	{
		m_memto = memto;
	}

	MemTo*getMemTo()
	{
		return m_memto;
	}

	void setMemTo(MemTo*memto)
	{
		m_memto = memto;
	}

private:
	MemTo *m_memto;
};

void main1()
{
	MemTo *m = NULL;
	Person *p1 = new Person("小于", 25);
	p1->printT();
	m = p1->CreatMemTo();
	p1->setName("老于");
	p1->setAge(50);
	p1->printT();
	p1->setMemTo(m);
	p1->printT();

}

void main2()
{
	careTaker *m = NULL;
	Person *p1 = new Person("小于", 25);
	p1->printT();
	m = new careTaker(p1->CreatMemTo());
	p1->setName("老于");
	p1->setAge(50);
	p1->printT();
	p1->setMemTo(m->getMemTo());
	p1->printT();

}

void main()
{
	main2();
}

main1、main2运行结果:


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页