您的位置:首页 > 其它

备忘录模式

2015-12-21 13:05 393 查看
// ConsoleApplication19.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

//C++后面使用的类要先声明?

/*负责存储GameRole对象的内部状态,并可防止GameRole以外的其他对象访问备忘录Memento。
备忘录有两个接口,Caretaker只能看见备忘录的窄借口,他只能将备忘录传递给其他对象。
Originator能够看到一个宽接口,允许他访问返回到先前状态所需的所有数据*/

class Memento
{
public:
int m_atk;
int m_magic;
int m_bld;

Memento(int a,int m,int b)
{
this->m_atk = a;
this->m_magic = m;
this->m_bld = b;
}
};

/*负责创建一个备忘录Memento,用以记录当前时刻它的内部状态,
并可使用备忘录恢复内部状态。GameRole可根据需要决定Memento
存储GameRole的哪些内部状态*/
class GameRole
{
public:
int atk;
int magicNum;
int bldNum;

GameRole(int a,int m,int b)
{
this->atk = a;
this->bldNum = b;
this->magicNum = m;
}
void RecoveryDataFrom(Memento* m)
{
atk = m->m_atk;
magicNum = m->m_magic;
bldNum = m->m_bld;
}

Memento* SetMementoData()
{
return new Memento(atk,magicNum,bldNum);
}

void Show()
{
cout<<atk<<magicNum<<bldNum<<endl;
}
};

/*负责保存好备忘录Memento,不能对备忘录的内容进行操作或检查*/
class Caretaker
{
public:
Memento *m;
};
int _tmain(int argc, _TCHAR* argv[])
{
GameRole *gr = new GameRole(100,100,100);
gr->Show();

Caretaker *m = new Caretaker();
m->m = gr->SetMementoData();

gr->atk =80;
gr->Show();

gr->RecoveryDataFrom(m->m);
gr->Show();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  备忘录