标签:
不破坏封装的情况下,捕获一个对象的内部状况,并在对象外部保存这个状态,以后可以恢复的原先保存的状态。相当于快照
涉及角色:
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 using namespace std; 5 6 //设计备忘录三大步骤 7 //1.设计记录的节点,存储记录,//记录鼠标,键盘的状态 8 //2.设计记录的存储,vector,list,map,set,链表,图,数组,树 9 //3.操作记录的类,记录节点状态,设置节点状态,显示状态,0.1秒记录一下 10 11 12 13 14 //备忘录的节点, 15 class Memo 16 { 17 public: 18 string state; 19 Memo(string state) //记录当前的状态, 20 { 21 this->state = state; 22 } 23 }; 24 25 class Originator//类的包含备忘录的节点 26 { 27 public: 28 string state; 29 void setMemo(Memo *memo) 30 { 31 state = memo->state; 32 } 33 Memo *createMemo() 34 { 35 return new Memo(state); 36 } 37 void show() 38 { 39 cout << state << endl; 40 } 41 }; 42 43 44 //备忘录的集合 45 class Caretaker 46 { 47 public: 48 vector<Memo *> memo; 49 void save(Memo *memo) 50 { 51 (this->memo).push_back(memo); 52 } 53 Memo *getState(int i) 54 { 55 56 return memo[i]; 57 } 58 }; 59 60 int main() 61 { 62 Originator *og = new Originator(); 63 Caretaker *ct = new Caretaker(); 64 65 og->state = "on"; 66 og->show(); 67 ct->save(og->createMemo()); 68 69 og->state = "off"; 70 og->show(); 71 ct->save(og->createMemo()); 72 73 og->state = "middle"; 74 og->show(); 75 ct->save(og->createMemo()); 76 77 og->setMemo(ct->getState(1)); 78 og->show(); 79 80 og->setMemo(ct->getState(2)); 81 og->show(); 82 cin.get(); 83 return 0; 84 }
标签:
原文地址:http://www.cnblogs.com/yangrlee/p/5188250.html