设计模式——备忘录模式(C++实现)

设计模式——备忘录模式(C++实现)

 #include <iostream>
#include <string>
#include <vector> using namespace std; class STMemento
{
private:
int iVitality;
public:
STMemento(){}
STMemento(int iVitality)
{
this->iVitality = iVitality;
} int GetVitality() const
{
return this->iVitality;
}
}; class STOriginator
{
private:
int iVitality;
string name;
public:
STOriginator(string strName, int iVit): iVitality(iVit), name(strName)
{ } STMemento* SaveState()
{
return new STMemento(iVitality);
} void RecoverState(const STMemento* stMemento)
{
this->iVitality = stMemento->GetVitality();
} void SetVitality(int iVit)
{
this->iVitality = iVit;
} void Show()
{
cout<< "Name: "<< name<< endl;
cout<< "Live: "<< iVitality<< endl;
}
}; class STCareTaker
{
private:
vector<STMemento*> vecStMemento; public:
void AddMemento(STMemento* stMemento)
{
vecStMemento.push_back(stMemento);
} STMemento* GetMemento(int Iindex)
{
if (Iindex >= vecStMemento.size())
return NULL;
else
return vecStMemento[Iindex];
}
}; int main(int argc, char* argv[])
{
STOriginator* pstOriginator = new STOriginator("xxx", );
cout<< "原始状态: "<< endl;
pstOriginator->Show(); STCareTaker* pstCareTaker = new STCareTaker();
pstCareTaker->AddMemento(pstOriginator->SaveState()); pstOriginator->SetVitality();
cout<< "战斗后状态: "<< endl;
pstOriginator->Show(); pstOriginator->RecoverState(pstCareTaker->GetMemento());
cout<< "归档后状态: "<< endl;
pstOriginator->Show(); return ;
}
/////////////////////////////
[root@ ~/learn_code/design_pattern/15_memento]$ ./memento
原始状态:
Name: xxx
Live: 战斗后状态:
Name: xxx
Live: 归档后状态:
Name: xxx
Live:
上一篇:计蒜客 1460.Ryuji doesn't want to study-树状数组 or 线段树 (ACM-ICPC 2018 徐州赛区网络预赛 H)


下一篇:Netty 服务端创建