這個題目算是比較經典的觀察者模式了,老鼠做爲一個Subject,主動發出跑的動做,緊跟着貓因爲老鼠的跑而發出叫聲,主人也被驚醒,在這裏貓跟主人都是被動的,是觀察者角色,代碼實現以下:this
1 class CSubject; 2 //觀察者 3 class CObserver 4 { 5 public: 6 CObserver(){} 7 virtual ~CObserver(){} 8 virtual void Update(CSubject* pSubject) = 0; 9 }; 10 11 //目標即主題,可理解爲因爲本對象變化致使其餘對象跟隨變化 12 class CSubject 13 { 14 public: 15 void Attach(CObserver* pO) 16 { 17 _ls.push_back(pO); 18 } 19 void Detach(CObserver* pO) 20 { 21 _ls.remove(pO); 22 } 23 void Notify() 24 { 25 for (list<CObserver*>::iterator it=_ls.begin();it!=_ls.end();it++) 26 { 27 (*it)->Update(this); 28 } 29 } 30 private: 31 list<CObserver*> _ls; 32 }; 33 34 //貓爲觀察者 35 class CCat:public CObserver 36 { 37 public: 38 CCat(){} 39 virtual ~CCat(){} 40 virtual void Update(CSubject* pSubject){ 41 Say(); 42 } 43 void Say() 44 { 45 printf("貓叫了\r\n"); 46 } 47 }; 48 49 //人爲觀察者 50 class CPerson:public CObserver 51 { 52 public: 53 CPerson(){} 54 virtual ~CPerson(){} 55 56 virtual void Update(CSubject* pSubject){ 57 Say(); 58 } 59 void Say() 60 { 61 printf("人醒了\r\n"); 62 } 63 }; 64 65 //老鼠爲主題 66 class CMouse:public CSubject 67 { 68 public: 69 70 void Say() 71 { 72 printf("老鼠叫了\r\n"); 73 Notify(); 74 } 75 };
1 int _tmain(int argc, _TCHAR* argv[]) 2 { 3 4 //老鼠跑貓叫主人醒 5 CMouse* pMouse = new CMouse(); 6 CCat* pCat = new CCat(); 7 CPerson* pPerson = new CPerson(); 8 9 pMouse->Attach(pCat); 10 pMouse->Attach(pPerson); 11 pMouse->Say(); 12 13 return 0; 14 }
main裏指針沒作釋放,如何優雅的釋放呢,還在考慮中,若是講究對稱美,那就是spa
1 int _tmain(int argc, _TCHAR* argv[]) 2 { 3 4 //老鼠跑貓叫主人醒 5 CMouse* pMouse = new CMouse(); 6 CCat* pCat = new CCat(); 7 CPerson* pPerson = new CPerson(); 8 9 pMouse->Attach(pCat); 10 pMouse->Attach(pPerson); 11 pMouse->Say(); 12 13 //對稱美,可是如此麻煩,還有其餘解決方法嗎 14 pMouse->Detach(pCat); 15 pMouse->Detach(pPerson); 16 delete pPerson; 17 delete pCat; 18 delete pMouse; 19 20 21 return 0; 22 }
歡迎各位發表觀點指針