设计模式 Design Parttern ——备忘录模式Memento

设计模式 Design Parttern ——备忘录模式Memento

http://blog.csdn.net/leeidea

//1:头文件

 

#ifndef _MEMENTO_H_VANEY_ #define _MEMENTO_H_VANEY_ #include using namespace std; /****************************************************************** 名称 :Memento.h 版本 :1.00 描述 :演示备忘录模式的概念 作者 :[email protected] http://blog.csdn.net/leeidea 日期 :2010年10月28日 版权 :[email protected] http://blog.csdn.net/leeide ******************************************************************/ /* 官方解释:The Memento captures and externalizes an object’s internal state, so the object can be restored to that state later. 我的理解:保存一个事物的状态,用于以后复原。 我的应用:游戏失败后可以接着打。 */ //需要复原的状态参数 class CState { public: CState(int p,int s,int sc):persons(p),stage(s),score(sc) { } public: //人数 int persons; //第几关 int stage; //分数 int score; }; //状态类 class CMemeto { private: CState* _state; public: CMemeto(CState* s) { if(s) { _state = new CState(0,0,0); _state->persons = s->persons; _state->stage = s->stage; _state->score = s->score; } } virtual ~CMemeto() { if(_state) delete _state; _state = 0; } public: CState* GetState() { return _state; } }; //事务 class CGame { public: CGame() { m_state = new CState(0,0,0); cout << "CGame()" << endl; } virtual ~CGame() { if(m_state) delete(m_state); m_state = 0; cout << "~CGame()" << endl; } public: virtual CMemeto* GetMemeto() { return new CMemeto(m_state); } virtual void Restore(CMemeto* m) { if(m) { if(!m_state) { m_state = new CState(0,0,0); } memset(m_state,0,sizeof(CState)); m_state->persons = m->GetState()->persons; m_state->stage = m->GetState()->stage; m_state->score = m->GetState()->score; cout << "Restore to person = " << m_state->persons << "stage = " << m_state->stage << "score = " << m_state->score << endl; } } virtual void ChangeState(int a, int b, int c) { if(!m_state) { m_state = new CState(0,0,0); } m_state->persons = a; m_state->stage = b; m_state->score = c; cout << "Change to person = " << a << "stage = " << b << "score = " << c << endl; } protected: CState* m_state; }; #define C_API extern "C" //用户 C_API int UsingMM(); #endif


//2:源文件

 

#include "Memento.h" C_API int UsingMM() { CGame* game = new CGame(); //游戏状态改变 game->ChangeState(10,3,1); //保存游戏状态 CMemeto* m = game->GetMemeto(); //游戏状态又改变 game->ChangeState(44,2,1); //还原到原来的状态 game->Restore(m); delete m; return 1; }


//3:用户文件main.c

 

extern int UsingMM(); //系统默认入口 int _tmain(int argc, _TCHAR* argv[]) { return UsingMM(); }

你可能感兴趣的:(设计模式 Design Parttern ——备忘录模式Memento)