存档模式 Memento
定义:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态
类型:行为类
类图:
class Memento{ public: Memento(int level,int life,int time):m_level(level),m_life(life),m_time(time){} Memento * GetState(){ return this; } int GetLevel(){ return m_level; } int Getlife(){ return m_life; } int Gettime(){ return m_time; } private: int m_level; int m_life; int m_time; }; class Role{ public: Role(int level,int life,int time):m_level(level),m_life(life),m_time(time){} void LoadMem(Memento * pmem){ m_level = pmem->GetLevel(); m_life = pmem->Getlife(); m_time = pmem->Gettime(); } Memento * CreateMem(){ return new Memento(m_level,m_life,m_time); } void Upgrade(){ this->m_level += 1 ; this->m_life += 10; this->m_time += 10; } void show(){ cout<<"~~~~~~~~state~~~~~~~~~~"<<endl; cout<<"level : "<<m_level<<endl; cout<<"life : "<<m_life<<endl; cout<<"time : "<<m_time<<endl; } private: int m_level; int m_life; int m_time; }; class ManagerMem{ public: void AddMem(Memento * p){ memvec.push_back(p); } Memento * GetMem(int index){ return memvec[index]; } ~ManagerMem(){ vector<Memento *>::iterator it = memvec.begin(); for(; it != memvec.end();it++) delete *it; } private: vector<Memento *> memvec; }; int main(int argc,char * argv[]){ ManagerMem * pmanager = new ManagerMem; Role * prole = new Role(1,20,30); prole->show(); prole->Upgrade(); prole->show(); cout<<"存档管理器添加存档:"<<endl; pmanager->AddMem(prole->CreateMem()); prole->Upgrade(); prole->show(); prole->Upgrade(); prole->show(); //断电了,升级失败,只能恢复原来的存档 cout<<"加载存档:"<<endl; prole->LoadMem(pmanager->GetMem(0)); prole->show(); delete prole; delete pmanager; }