行为型_备忘录模式(Memento)
作用场景:
当意图在对象外面保存对象的内部状态,但是又不想破坏对象的封装性,就可以考虑备忘录模式。
解释:
其参与者包括
1、Memnto(备忘录,如下列CountMemento )
2、Originator(原发器,如下列Counter ),
3、Caretaker(管理者,如下列CounterCaretaker )
Memnto用于保存Originator内部状态,其私有窄接口只能有Originator访问,Caretaker只能访问Memnto的宽接口。所以通常Memnto和Originator是友元。
例如;
一个计数器,有个初始状态值,可以操作计数增加,后来我们想这个计数器或者另一个计数器也恢复成这个初始值。我们用备忘录模式解决这个问题
类:
Counter 计数器
CountMemento 计数器备忘录
CounterCaretaker 操作者
类图:
代码:
#include <iostream> class CountMemento { public: CountMemento(int count) :m_count(count) {} ~CountMemento() {}; private: friend class Counter; int getCount() { return m_count; } int m_count; }; class Counter { public: Counter(int count) :m_count(count) {} ~Counter() {} CountMemento* saveState() { return new CountMemento(m_count); } void recoverState(CountMemento* p_countMemento) { m_count = p_countMemento->getCount(); } void increase() { m_count++; } void show() { printf("count :%d\n", m_count); } private: int m_count; }; class CounterCaretaker { public: void setCountMemento(CountMemento* p_countMemento) { m_countMemento = p_countMemento; } CountMemento* getCountMemento() { return m_countMemento; } private: CountMemento* m_countMemento; }; int main() { CounterCaretaker counterCaretaker; Counter counter(); counter.show(); printf("save counter...\n"); counterCaretaker.setCountMemento(counter.saveState()); printf("start incresing...\n"); ; i < ; ++i) { counter.increase(); } printf("after incresing...\n"); counter.show(); printf("recovering...\n"); counter.recoverState(counterCaretaker.getCountMemento()); counter.show(); system("pause"); }