C++設計模式——觀察者模式
觀察者模式:定義了對象之閒的一對多依賴,這樣一來,儅一個對象改變狀態時,它的所有依賴者都會收到通知並自動更新。
觀察者模式的類圖:
代碼示例 :利用WeatherData對象取得數據,更新concreteobserver 並顯示出來,以下是代碼示例:
1 #ifndef SUBJECT_H 2 #define SUBJECT_H 3 #include "observer.h" 4 class subject 5 { 6 public: 7 subject(); 8 virtual ~subject(); 9 virtual void registerObserver(Observer* o) = 0; 10 virtual void removeObserver(Observer* o)= 0; 11 virtual void notifyObservers() = 0; 12 }; 13 14 #endif // SUBJECT_H
1 #ifndef OBSERVER_H 2 #define OBSERVER_H 3 4 class Observer 5 { 6 public: 7 Observer(); 8 virtual ~Observer(); 9 virtual void update(float temp,float humidity,float pressure) = 0; 10 11 }; 12 13 #endif // OBSERVER_H
1 #include "weather_data.h" 2 3 WeatherData::WeatherData() 4 { 5 m_vecObserver.clear(); 6 } 7 WeatherData::~WeatherData() 8 { 9 10 } 11 12 void WeatherData::registerObserver(Observer *o) 13 { 14 m_vecObserver.append(o); 15 16 } 17 18 void WeatherData::removeObserver(Observer* o) 19 { 20 int index = m_vecObserver.indexOf(o); 21 if(index >=0) 22 { 23 m_vecObserver.remove(index); 24 } 25 } 26 27 void WeatherData::notifyObservers() 28 { 29 for(int i = 0;i < m_vecObserver.size();i++) 30 { 31 m_vecObserver.at(i)->update(this->temperature,this->humidity,this->pressure); 32 } 33 } 34 35 void WeatherData::setMeasureMents(float temperature, float humidity, float pressure) 36 { 37 this->temperature = temperature; 38 this->humidity = humidity; 39 this->pressure = pressure; 40 measurementsChanged(); 41 } 42 float WeatherData::getTemperature() 43 { 44 return this->temperature; 45 } 46 47 float WeatherData::getHumidity() 48 { 49 return this->humidity; 50 } 51 52 float WeatherData::getPressure() 53 { 54 return this->pressure; 55 } 56 57 void WeatherData::measurementsChanged() 58 { 59 notifyObservers(); 60 }
1 #include "concreteobserver.h" 2 #include <QDebug> 3 #include <weather_data.h> 4 ConcreteObserver::ConcreteObserver(subject *weatherData) 5 { 6 this->weatherData = weatherData; 7 weatherData->registerObserver(this); 8 9 } 10 11 void ConcreteObserver::update(float temp, float humidity, float pressure) 12 { 13 this->temperature = temp; 14 this->humidity = humidity; 15 display(); 16 } 17 18 void ConcreteObserver::display() 19 { 20 qDebug()<<"當前溫度:"<<this->temperature<<"當前海拔:"<<this->humidity; 21 }
1 #include <QCoreApplication> 2 #include "concreteobserver.h" 3 #include "weather_data.h" 4 int main(int argc, char *argv[]) 5 { 6 QCoreApplication a(argc, argv); 7 WeatherData* subject = new WeatherData(); 8 ConcreteObserver* observer = new ConcreteObserver(subject); 9 subject->setMeasureMents(20,30,40); 10 subject->setMeasureMents(40,50,20); 11 12 13 return a.exec(); 14 }
參考資料:HeadFirst 設計模式
源碼:
宣言:在此记录自己学习过程中的心得体会,同时积累经验,不断提高自己!
文章未经说明均属原创,学习笔记可能有大段的引用,一般会注明参考文献。 欢迎大家留言交流。转载请注明出处。