/*
备忘录模式:在不破坏一个对象的封装性的前提下,获取一个对象的内部状态,并将其保存在对象之外,
使得对象可以恢复到原先保存的状态。
Created by Phoenix_FuliMa
*/
#include <iostream>
#include <string>
using namespace std;
class Memento
{
private:
string state;
public:
Memento(string state)
:state(state)
{}
string GetState()
{
return state;
}
void SetState(string state)
{
this->state = state;
}
};
class CareTaker
{
private:
Memento *memento;
public:
void SetMemento(Memento *memento)
{
this->memento = memento;
}
Memento* GetMemento()
{
return this->memento;
}
};
class Originator
{
private:
string state;
public:
Originator(string state)
{
this->state = state;
}
void RestoreMemento(Memento *memento)
{
state = memento->GetState();
}
Memento *CreateMemento()
{
return new Memento(state);
}
void SetState(string state)
{
this->state = state;
}
void ShowState()
{
cout<< this->state <<endl;
}
};
int main()
{
Originator *originator = new Originator("2012年11月11日,光棍节,一个人,没有女朋友");
CareTaker *caretaker = new CareTaker();
caretaker->SetMemento(originator->CreateMemento());
cout<<"2012年11月11日,光棍节早晨的状态是:"<<endl;
originator->ShowState();
originator->SetState("中午参加同学婚礼去了,锦府盐帮饭店");
originator->ShowState();
cout<<"晚上回来的状态是"<<endl;
originator->RestoreMemento(caretaker->GetMemento());
originator->ShowState();
cout<<"跟早晨一样,嗨"<<endl;
system("pause");
return 0;
}