观察者模式(observer)
一、代码示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <vector> 3 #include <string> 4 using namespace std; 5 6 ///抽象一个Subject主题 7 ///观察者 8 class Observer { 9 public: 10 virtual void update(string m_Temp, string m_Humi) = 0; 11 protected: 12 Observer() {} 13 }; 14 class Subject { 15 public: 16 virtual void registerObserver(Observer* pObj)=0; 17 virtual void removeObserver(Observer* pObj)=0; 18 virtual void noitfyObserver()=0; 19 protected: 20 Subject(){} 21 }; 22 23 class WeatherData :public Subject { 24 public: 25 WeatherData(string Temp, string Humi) : m_Temp(Temp), m_Humi(Humi) { 26 } 27 void registerObserver(Observer* pObj) { 28 m_observers.push_back(pObj); 29 } 30 void removeObserver(Observer* pObj) { 31 auto iter = find(m_observers.begin(), m_observers.end(), pObj); 32 if (iter != m_observers.end()) { 33 m_observers.erase(iter); 34 } 35 } 36 void noitfyObserver() { 37 //逐个遍历调用Observer的update方法 38 for (vector<Observer*>::iterator iter = m_observers.begin();iter != m_observers.end();iter++) { 39 (*iter)->update(m_Temp, m_Humi); 40 41 } 42 } 43 44 void setData(string Temp, string Humi) { 45 m_Temp = Temp; 46 m_Humi = Humi; 47 noitfyObserver(); 48 } 49 private: 50 vector<Observer*> m_observers; 51 string m_Temp;//温度 52 string m_Humi;//湿度 53 }; 54 55 56 57 58 //CocreteObserver 59 class PCDisplay:public Observer { 60 public: 61 void update(string m_Temp, string m_Humi) { 62 cout << "我是PC端的显示GUI,当前的温度为" << m_Temp << "湿度为" << m_Humi << endl; 63 } 64 65 PCDisplay(WeatherData* pWeatherData) { 66 m_pWeatherData = pWeatherData; 67 m_pWeatherData->registerObserver(this); 68 } 69 private: 70 WeatherData* m_pWeatherData; 71 }; 72 73 74 75 class MobileDisplay :public Observer { 76 public: 77 void update(string m_Temp, string m_Humi) { 78 cout << "我是Mobile端的显示GUI,当前的温度为" << m_Temp << "湿度为" << m_Humi << endl; 79 } 80 81 MobileDisplay(WeatherData* pWeatherData) { 82 m_pWeatherData = pWeatherData; 83 m_pWeatherData->registerObserver(this); 84 } 85 private: 86 WeatherData* m_pWeatherData; 87 }; 88 89 90 int main(void) { 91 WeatherData* pWD = new WeatherData("22C", "65%"); 92 PCDisplay* pPCDisplay = new PCDisplay(pWD); 93 MobileDisplay* pMobile = new MobileDisplay(pWD); 94 95 pWD->setData("38C", "55%"); 96 pWD->removeObserver(pMobile); 97 pWD->setData("31", "44%"); 98 99 system("pause"); 100 return 0; 101 }