这个题目算是比较经典的观察者模式了,老鼠作为一个Subject,主动发出跑的动作,紧跟着猫由于老鼠的跑而发出叫声,主人也被惊醒,在这里猫跟主人都是被动的,是观察者角色,代码实现如下:
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里指针没做释放,如何优雅的释放呢,还在考虑中,如果讲究对称美,那就是
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 }
欢迎各位发表观点
大部分转载 小部分自写