WeatherData.h
#ifndef WEATHERDATA_H_INCLUDED
#define WEATHERDATA_H_INCLUDED #include <set>
#include "Display.h" class WeatherData
{
public:
void measurementsChanged();
void registerObserver( Display *p_display );
void removeObserver( Display *p_display ); private:
int getTemperature() { return ; }
int getHumidity() { return ; }
int getPressure() { return ; } std::set<Display *> m_p_displays;
}; #endif // WEATHERDATA_H_INCLUDED
WeatherData.cpp
#include "WeatherData.h" void WeatherData::measurementsChanged()
{
for ( std::set<Display *>::iterator it = m_p_displays.begin(); it != m_p_displays.end(); it++ )
{
(*it)->update( getTemperature(), getHumidity(), getPressure() );
}
} void WeatherData::registerObserver( Display *p_display )
{
m_p_displays.insert( p_display );
} void WeatherData::removeObserver( Display *p_display )
{
m_p_displays.erase( p_display );
}
Display.h
#ifndef DISPLAY_H_INCLUDED
#define DISPLAY_H_INCLUDED class Display
{
public:
virtual void update( int temp, int humidity, int pressure ) = ;
}; #endif // DISPLAY_H_INCLUDED
CurrentConditionsDisplay.h
#ifndef CURRENTCONDITIONSDISPLAY_H_INCLUDED
#define CURRENTCONDITIONSDISPLAY_H_INCLUDED #include <iostream>
#include "Display.h" class CurrentConditionsDisplay : public Display
{
public:
void update( int temp, int humidity, int pressure ) { std::cout << "CurrentConditionsDisplay " << temp << "-" << humidity << "-" << pressure << std::endl; }
}; #endif // CURRENTCONDITIONSDISPLAY_H_INCLUDED
StatisticsDisplay.h
#ifndef STATISTICSDISPLAY_H_INCLUDED
#define STATISTICSDISPLAY_H_INCLUDED #include <iostream>
#include "Display.h" class StatisticsDisplay : public Display
{
public:
void update( int temp, int humidity, int pressure ) { std::cout << "StatisticsDisplay " << temp << "-" << humidity << "-" << pressure << std::endl; }
}; #endif // STATISTICSDISPLAY_H_INCLUDED
ForcastDisplay.h
#ifndef FORCASTDISPLAY_H_INCLUDED
#define FORCASTDISPLAY_H_INCLUDED #include <iostream>
#include "Display.h" class ForcastDisplay : public Display
{
public:
void update( int temp, int humidity, int pressure ) { std::cout << "ForcastDisplay " << temp << "-" << humidity << "-" << pressure << std::endl; }
}; #endif // FORCASTDISPLAY_H_INCLUDED
main.cpp
#include "WeatherData.h"
#include "CurrentConditionsDisplay.h"
#include "StatisticsDisplay.h"
#include "ForcastDisplay.h" int main()
{
WeatherData weather_data; CurrentConditionsDisplay current_conditions_display;
StatisticsDisplay statistics_display;
ForcastDisplay forcast_display; weather_data.registerObserver( ¤t_conditions_display );
weather_data.registerObserver( &statistics_display );
weather_data.registerObserver( &forcast_display ); weather_data.measurementsChanged(); weather_data.removeObserver( &statistics_display ); weather_data.measurementsChanged(); return ;
}