观察者模式之比喻:ios
1 /** 2 * Define observer mode 3 */ 4 #include <iostream> 5 #include <list> 6 using namespace std; 7 8 #ifndef NULL 9 #define NULL ((void*)0) 10 #endif 11 12 // 各类消息的基类 13 class DOBject 14 { 15 public: 16 DOBject(int value){ 17 value = value; 18 } 19 ~DOBject(); 20 private: 21 public: 22 /* data */ 23 int value; 24 public: 25 /* Function */ 26 bool operator ==(const DOBject &otherObject){ 27 return (value==otherObject.value); 28 } 29 }; 30 // 类员工类 31 class DListener 32 { 33 public: 34 DListener(/*arguments*/); 35 ~DListener(); 36 /* data */ 37 /* Respond to notify */ 38 public: 39 void OnNotify(DObject *object) 40 { 41 // Do something 42 return ; 43 } 44 }; 45 // 类前台类 46 class DObserverObject 47 { 48 public: 49 DObserverObject(/*arguments*/){ 50 m_pListeners = new List<DListener*>(); 51 m_pObject = new DObject(); 52 } 53 ~DObserverObject(){ 54 if (NULL != m_pObject) 55 { 56 /* code */ 57 delete m_pObject; 58 } 59 if (NULL != m_pListeners) 60 { 61 /* 须要循环把list里面的注册者都清理掉 */ 62 for(int i=0, count=m_pListeners->size(); i < count; ++i){ 63 delete m_pListeners->get(i); 64 m_pListeners->get(i) = NULL; 65 } 66 delete m_pListeners; 67 } 68 } 69 // 员工注册 70 void Registe(DListener *newListener){ 71 m_pListeners->add(newListener); 72 } 73 // 取消注册 74 void UnRegiste(DListener *newListener){ 75 m_pListeners->remove(newListener); 76 } 77 //通知员工 78 void SendNotify(void){ 79 for (int i = 0; i < m_pListeners.size(); ++i) 80 { 81 /* 须要循环将全部注册的员工都通知到 */ 82 m_pListeners[i]->OnNotify(m_pObject); 83 } 84 } 85 // 通常对于这个有俩种传递数据的方式,推或者拉 86 // 对于推方式,则SendNotify须要加参数; 87 // 对于拉方式,则SendNotify不须要参数,由员工本身经过GetValue去取 88 DObject *GetValue(void){ 89 return m_pObject; 90 } 91 //发生了什么事情,老板来了,或者快递来了 92 void SetValue(DObject *newObject){ 93 if (m_pObject!=*newObject) 94 { 95 /* code */ 96 m_pObject->value = newObject->value; 97 SendNotify(newObject); 98 } 99 } 100 /* data */ 101 private: 102 List<DListener*> *m_pListeners; 103 DObject *m_pObject; 104 };
对于以上代码可能对于list的使用存在问题,还未彻底测试,有兴趣的能够本身进行测试,也能够本身本身采用其余数据结构!web
谢谢!数据结构