![](https://img-blog.csdn.net/20150418133019571?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY2djb2Rlcg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
#ifndef __WEATHER_H__
#define __WEATHER_H__
#include <list>
#include <iostream>
using namespace std;
class DisplayElement
{
public:
DisplayElement(){}
virtual ~DisplayElement(){}
virtual void display(){}
};
class Subject;
class Observer
{
public:
Observer(){}
virtual ~Observer(){}
virtual void update(float temp, float humidit, float pressure){}
};
class CurrentWeatherDisplay:public Observer, public DisplayElement
{
private:
float temperature;
float humidity;
float pressure;
Subject *weatherData;
public:
CurrentWeatherDisplay(Subject *wd);
virtual ~CurrentWeatherDisplay(){}
virtual void CurrentWeatherDisplay::display()
{
std::cout << "This is Current" << temperature << " " << humidity << " " << pressure << endl;
}
virtual void CurrentWeatherDisplay::update(float temp, float hum, float pres)
{
temperature = temp;
humidity = hum;
pressure = pres;
display();
}
};
#endif
#ifndef __SUBJECT_H__
#define __SUBJECT_H__
#include <list>
#include <iostream>
#include "Observer.h"
using namespace std;
class Subject
{
public:
Subject(){}
virtual ~Subject(){}
virtual void registerObserver(Observer *obs){}
virtual void removeObserver(Observer *obs){}
virtual void notifyObserver(){}
};
class WeatherData : public Subject
{
private:
std::list<Observer*>observer;
float temperature;
float humidity;
float pressure;
public:
WeatherData(){}
virtual ~WeatherData(){}
virtual void registerObserver(Observer *obs){ observer.push_back(obs); }
virtual void removeObserver(Observer *obs) { observer.remove(obs);}
virtual void notifyObserver()
{
std:list<Observer *>::iterator it = observer.begin();
for (; it != observer.end(); it++)
{
(*it)->update(temperature, humidity, pressure);
}
}
void measurementsChanged(){ notifyObserver();}
void setMeasurements(float temp, float hum, float pre)
{
temperature = temp;
humidity = hum;
pressure = pre;
measurementsChanged();
}
};
CurrentWeatherDisplay::CurrentWeatherDisplay(Subject *wd)
{
weatherData = wd;
weatherData->registerObserver(this);
}
#endif
#include <iostream>
#include "Subject.h"
using namespace std;
int main()
{
WeatherData *wd = new WeatherData();
CurrentWeatherDisplay * cu = new CurrentWeatherDisplay(wd);
wd->setMeasurements(10, 20, 30);
wd->setMeasurements(20, 40, 80);
wd->setMeasurements(100, 200, 300);
return 0;
}