初学设计模式之观察者模式
观察者模式代码例子
1 //观察者模式 2 #include<iostream> 3 #include<list> 4 using namespace std; 5 6 class MasterListener 7 { 8 public: 9 virtual void OnChange() 10 { 11 }; 12 13 }; 14 15 class Student1:MasterListener 16 { 17 public: 18 void OnChange() 19 { 20 cout<<"同学A不看小说了"<<endl; 21 }; 22 }; 23 24 25 class Student2:MasterListener 26 { 27 public: 28 void OnChange() 29 { 30 cout<<"同学B不玩手机了"<<endl; 31 }; 32 }; 33 34 35 class Master 36 { 37 protected: 38 list<MasterListener*>m_list; 39 //MasterListener* m_MasterListenerPtr; 40 public: 41 void setListener(MasterListener* m_MasterListenerPtr) 42 { 43 m_list.push_back(m_MasterListenerPtr); 44 //m_MasterListenerPtr=m_MasterListener; 45 }; 46 void Notify() 47 { 48 for(list<MasterListener*>::iterator iter=m_list.begin();iter!=m_list.end();iter++) 49 { 50 (*iter)->OnChange(); 51 }; 52 }; 53 }; 54 55 int main() 56 { 57 Student1 *m_student1=new Student1; 58 Student2 *m_student2=new Student2; 59 Master m_master; 60 m_master.setListener(m_student1); 61 m_master.setListener(m_student2); 62 63 cout<<"老师来了"<<endl; 64 m_master.Notify(); 65 66 getchar(); 67 return 0; 68 };