概述
备忘录模式能记录一个对象的内部状态,当用户后悔时能撤销当前操作,使数据恢复到它原先的状态。
定义
在不违反封装的情况下,Memento捕获并外部化了对象的内部状态,以便以后可以将对象恢复到此状态。该模式具有行为目的,并且适用于对象。
角色
Memento:
备忘录类Originator:
发起人类CareTaker:
管理者类
场景
- 必须保存对象状态的快照,以便以后可以将其恢复到该状态
- 获取状态的直接接口将暴露实现细节并破坏对象的封装
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
//备忘录类 class Memento { private: friend class Originator; Memento(const int s) : state(s) { } void setState(const int s) { state = s; } int getState() { return state; } //... private: int state; //... }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//发起人类 class Originator { public: void setState(const int s) { std::cout << "set state to" << s << " " << std::endl; state = s; } int getState() { return state; } void setMemento(Memento* const m) { state = m->getState(); } Memento * createMemento() { return new Memento(state); } private: int state; //... }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
//管理者类 class CareTaker { public: CareTaker(Originator * const o):originator(o) { } ~CareTaker() { for(unsigned int i = 0;i < history.size();i++) delete history.at(i); history.clear(); } void save() { std::cout << "save state." << std::endl; history.push_back(originator->createMemento()); } void undo() { Memento * m = history.back(); originator->setMemento(m); std::cout << "undo state." << std::endl; history.pop_back(); delete m; } //... private: Originator * originator; std::vector<Memento*> history; //... }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
auto main()->int { Originator * originator = new Originator(); CareTaker * caretaker = new CareTaker(originator); originator->setState(1); caretaker->save(); originator->setState(2); caretaker->save(); originator->setState(3); caretaker->undo(); std::cout << "actual state is " << originator->getState() << "." << std::endl; delete originator; delete caretaker; return 0; } |
本文为原创文章,版权归Aet所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ 行为型:模板方法模式09/25
- ♥ 行为型:策略模式09/07
- ♥ 结构型:外观模式09/24
- ♥ 架构模式:MVC模式07/27
- ♥ 架构模式:MVVM模式07/27
- ♥ 结构型:代理模式09/23