设计模式系列4-----C++实现备忘录模式(Memento Pattern)
什么是备忘录模式?
Without violating encapsulation, capture and externalize an object’s internal state so that the object can be returned to this state later.
其实‘人’如其名,备忘模式就是为了对一个对象做备忘,允许做类似“重播”、“倒带”等操作。能用这种模式的前提是需要备忘的对象能够抽象出一个状态对象。而且备忘录模式也不会违背封装原则公开内部状态。
类图结构:
Originator即是需要备忘的类,它里面包含内部状态state对象。Originator能够通过createMemento创建保存点,也可以通过setMemento从给定的备忘回复内部状态。Caretaker负责保存备忘。
Example:
例子模拟游戏里面备忘人物的移动,当然这里为了方便人物的状态简化为只有坐标,当需要备忘的地方,可以备忘人物的状态,只有可以通过此来恢复。代码如下:
#include <iostream> #include <vector> using namespace std; struct State { public: State(int xx, int yy) : x(xx), y(yy) {} friend ostream& operator << (ostream& out, const State& state) { out << state.x << ", " << state.y; return out; } int x; int y; }; class Memento { public: Memento(State* pState) : m_pState(pState) {} State* getState() const { return m_pState; } private: State* m_pState; }; class Player { public: void setState(State* pState) { m_pState = pState; cout << "Player move to " << *pState << endl; } Memento* createMemo() { return new Memento(m_pState); } void setMemo(Memento* pMemo) { setState(pMemo->getState()); } private: State* m_pState; }; class Recorder { public: Recorder(Player* pPlayer) : m_pPlayer(pPlayer) {} void record() { m_memoList.push_back(m_pPlayer->createMemo()); } void replay() { cout << "\nbegin replay..." << endl; vector<Memento*>::const_iterator iter = m_memoList.begin(); for (; iter != m_memoList.end(); ++iter) { Memento* pMemo = *iter; m_pPlayer->setMemo(pMemo); } cout << endl; } void rewind() { cout << "\nbegin rewind..." << endl; vector<Memento*>::const_reverse_iterator iter = m_memoList.rbegin(); for (; iter != m_memoList.rend(); ++iter) { Memento* pMemo = *iter; m_pPlayer->setMemo(pMemo); } } void reset() { cout << "\nreset recorder" << endl; vector<Memento*>::iterator iter = m_memoList.begin(); for (; iter != m_memoList.end(); ++iter) { Memento* pMemo = *iter; delete pMemo; } m_memoList.clear(); } private: Player* m_pPlayer; vector<Memento*> m_memoList; }; int main() { State* pState1 = new State(1, 2); State* pState2 = new State(3, 4); Player* pPlayer = new Player(); Recorder* pRecorder = new Recorder(pPlayer); pPlayer->setState(pState1); pRecorder->record(); pPlayer->setState(pState2); pRecorder->record(); pRecorder->replay(); pRecorder->rewind(); pRecorder->reset(); delete pState1; delete pState2; delete pPlayer; delete pRecorder; return 0; }
运行结果如下:
参考资料:
PatternCraft – Memento Pattern
<<Design Patterns—Elements of Reusable Object-Oriented Software>>
posted on 2011-12-07 20:31 GraphicsMe 阅读(489) 评论(0) 编辑 收藏 举报