// Memento.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
typedef string STATE;
class Memento;
class Originator
{
public:
Originator(){}
Originator(const STATE& st):m_state(st)
{
}
virtual ~Originator(){}
Memento* CreateMemento();
void SetMemento(Memento* pMemeto);
STATE getState()
{
return m_state;
}
void setState(const STATE& st )
{
m_state=st;
}
void printState()
{
cout<<m_state<<endl;
}
private:
STATE m_state;
};
class Memento
{
private:
friend class Originator;
Memento(const STATE& st);
void setState(const STATE& st)
{
m_state=st;
}
STATE getState();
STATE m_state;
};
Memento::Memento(const STATE& st)
{
m_state=st;
}
STATE Memento::getState()
{
return m_state;
}
void Originator::SetMemento(Memento* pMemento)
{
if(NULL!=pMemento)
m_state=pMemento->getState();
}
Memento *Originator::CreateMemento()
{
return new Memento(m_state);
}
int _tmain(int argc, _TCHAR* argv[])
{
// 创建一个原发器
Originator* pOriginator = new Originator("old state");
pOriginator->printState();
// 创建一个备忘录存放这个原发器的状态
Memento *pMemento = pOriginator->CreateMemento();
// 更改原发器的状态
pOriginator->setState("new state");
pOriginator->printState();
// 通过备忘录把原发器的状态还原到之前的状态
pOriginator->SetMemento(pMemento);
pOriginator->printState();
delete pOriginator;
delete pMemento;
return 0;
}