1 #include 2 #include 3 #include 4 #include 5 #include 6 7 using namespace std; 8 9 class STSubject; 10 11 //觀察者 12 class STObserver 13 { 14 public: 1... ...
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <iterator> 5 #include <string> 6 7 using namespace std; 8 9 class STSubject; 10 11 //觀察者 12 class STObserver 13 { 14 public: 15 virtual void Update() = 0; 16 }; 17 18 class STConcreteObserverA: public STObserver 19 { 20 public: 21 virtual void Update() 22 { 23 cout<< "ConcreteObserverA Get Subject: "<< endl; 24 } 25 }; 26 27 class STConcreteObserverB: public STObserver 28 { 29 public: 30 virtual void Update() 31 { 32 cout<< "ConcreteObserverB Get Subject: "<< endl; 33 } 34 }; 35 36 37 //目標 38 class STSubject 39 { 40 public: 41 void Attach(STObserver* pstObserver) 42 { 43 m_vecObj.push_back(pstObserver); 44 } 45 void Detach(STObserver* pstObserver) 46 { 47 typeof(m_vecObj.begin()) it = find(m_vecObj.begin(), m_vecObj.end(), pstObserver); 48 if (it != m_vecObj.end()) 49 m_vecObj.erase(it); 50 } 51 void Notify() 52 { 53 for (size_t i = 0; i < m_vecObj.size(); i++) 54 { 55 m_vecObj[i]->Update(); 56 } 57 } 58 59 virtual string GetName() = 0; 60 61 private: 62 vector<STObserver*> m_vecObj; 63 }; 64 65 class STConcreteSubjectA: public STSubject 66 { 67 public: 68 virtual string GetName() 69 { 70 return "ConcreteSubjectA"; 71 } 72 73 }; 74 75 int main(int argc, char* argv[]) 76 { 77 STSubject* pstSubjectA = new STConcreteSubjectA(); 78 STObserver* pstObserverA = new STConcreteObserverA(); 79 STObserver* pstObserverB = new STConcreteObserverB(); 80 81 pstSubjectA->Attach(pstObserverA); 82 pstSubjectA->Attach(pstObserverB); 83 84 pstSubjectA->Notify(); 85 86 pstSubjectA->Detach(pstObserverB); 87 pstSubjectA->Notify(); 88 89 return 0; 90 } 91 ////////////////////////////////// 92 [root@ ~/learn_code/design_pattern/12_observer]$ ./observer 93 ConcreteObserverA Get Subject: 94 ConcreteObserverB Get Subject: 95 ConcreteObserverA Get Subject: