作用场景:
当意图在对象外面保存对象的内部状态,但是又不想破坏对象的封装性,就可以考虑备忘录模式。
解释:
其参与者包括
1、Memnto(备忘录,如下列CountMemento )
2、Originator(原发器,如下列Counter ),
3、Caretaker(管理者,如下列CounterCaretaker )
Memnto用于保存Originator内部状态,其私有窄接口只能有Originator访问,Caretaker只能访问Memnto的宽接口。所以通常Memnto和Originator是友元。
例如;
一个计数器,有个初始状态值,可以操作计数增加,后来我们想这个计数器或者另一个计数器也恢复成这个初始值。我们用备忘录模式解决这个问题
类:
Counter 计数器
CountMemento 计数器备忘录
CounterCaretaker 操作者
类图:
代码:
1 #include <iostream> 2 class CountMemento 3 { 4 public: 5 CountMemento(int count) :m_count(count) {} 6 ~CountMemento() {}; 7 private: 8 friend class Counter; 9 int getCount() 10 { 11 return m_count; 12 } 13 int m_count; 14 }; 15 class Counter 16 { 17 public: 18 Counter(int count) :m_count(count) {} 19 ~Counter() {} 20 CountMemento* saveState() 21 { 22 return new CountMemento(m_count); 23 } 24 void recoverState(CountMemento* p_countMemento) 25 { 26 m_count = p_countMemento->getCount(); 27 } 28 void increase() { m_count++; } 29 void show() { printf("count :%d\n", m_count); } 30 private: 31 int m_count; 32 }; 33 34 class CounterCaretaker 35 { 36 public: 37 void setCountMemento(CountMemento* p_countMemento) 38 { 39 m_countMemento = p_countMemento; 40 } 41 CountMemento* getCountMemento() 42 { 43 return m_countMemento; 44 } 45 private: 46 CountMemento* m_countMemento; 47 }; 48 49 int main() 50 { 51 CounterCaretaker counterCaretaker; 52 Counter counter(20); 53 counter.show(); 54 printf("save counter...\n"); 55 counterCaretaker.setCountMemento(counter.saveState()); 56 printf("start incresing...\n"); 57 for (int i = 0; i < 5; ++i) 58 { 59 counter.increase(); 60 } 61 printf("after incresing...\n"); 62 counter.show(); 63 printf("recovering...\n"); 64 counter.recoverState(counterCaretaker.getCountMemento()); 65 counter.show(); 66 system("pause"); 67 }
原文地址:https://www.cnblogs.com/ho966/p/10091017.html
时间: 2024-10-30 11:06:32