设计模式学习_气象站观察者模式
Posted Leslie X徐
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式学习_气象站观察者模式相关的知识,希望对你有一定的参考价值。
观察者模式
概述
由一个主题和若干观察者组成
功能:当主题更新数据时,同步更新数据到已订阅的各个观察者那边,并显示.
气象站
主题:
class Subject{
public:
virtual void registerObserver(Observer*)=0;
virtual void removeObserver(Observer*)=0;
virtual void notifyObservers()=0;
};
观察者:
class Observer{
public:
virtual void update(float,float)=0;
};
其他显示组件接口
class DisplayElement{
public:
virtual void display()=0;
};
主题气象站实现:
class WeatherData :
public Subject
{
private:
vector<Observer*> observers;
float temperature=0;
float humidity=0;
public:
WeatherData(){
}
void registerObserver(Observer* o){
observers.push_back(o);
}
void removeObserver(Observer* o){
vector<Observer*>::iterator it;
for(it=observers.begin(); it!=observers.end();++it)
if(*it==o) observers.erase(it);
}
void notifyObservers(){
for(auto i : observers){
Observer* o = i;
o->update(this->temperature, this->humidity);
}
}
void measurementsChanged(){
notifyObservers();
}
void setMeasurements(float temp, float hum){
this->temperature = temp;
this->humidity = hum;
measurementsChanged();
}
};
观察者实现:
class CurrentConditionDisplay :
public Observer,
public DisplayElement
{
private:
float temperature=0;
float humidity=0;
Subject *weatherData=nullptr;
public:
CurrentConditionDisplay(Subject *weather){
this->weatherData = weather;
this->weatherData->registerObserver(this);
}
void update(float temp, float hum){
this->temperature = temp;
this->humidity = hum;
display();
}
void display(){
cout<<"Current Conditions: "<<endl<<
"temperature: "<<this->temperature <<endl<<
"humidity: "<<this->humidity<<endl;
}
void detach(){
this->weatherData->removeObserver(this);
}
};
主函数测试:
int main(int argc, char **argv)
{
WeatherData weatherdata;
CurrentConditionDisplay cur1(&weatherdata);
CurrentConditionDisplay cur2(&weatherdata);
weatherdata.setMeasurements(12.5,23.5);
cur1.detach();
weatherdata.setMeasurements(24,27);
return 0;
}
与DTH11联合测试
/*
* 气象站.cxx
*
*/
#include "Observer.h"
#include "DTH11.h"
int main(int argc, char **argv)
{
float temp;
float hum;
wiringPiStart();
WeatherData weatherdata;
CurrentConditionDisplay cur1(&weatherdata);
while(1){
delay(2000);
getDTH(&temp,&hum);
weatherdata.setMeasurements(temp,hum);
}
return 0;
}
输出:
Current Conditions:
temperature: 32.1
humidity: 57
error2
Current Conditions:
temperature: 143.19
humidity: 64.183
Current Conditions:
temperature: 32.1
humidity: 56
以上是关于设计模式学习_气象站观察者模式的主要内容,如果未能解决你的问题,请参考以下文章