首页 > 代码库 > 设计模式入门,观察者模式,c++代码实现
设计模式入门,观察者模式,c++代码实现
// test02.cpp : Defines the entry point for the console application.
//
//设计模式第2章 观察者模式
#include "stdafx.h"
#include <vector>
using namespace std;
class Observer;
class Subject{
public:
virtual void registerObjecet(Observer* o) {};
void removeObserver(Observer o);
void notifyObservers();
};
class Observer
{
public:
virtual void update(float temp,float humidity,float pressure){};
bool operator == (const Observer * d)//重载==
{
return this == d;
}
};
class DisplayElement{
public:
void display();
};
class WeatherData : public Subject
{
private:
vector<Observer*> observers;
vector<Observer*>::iterator iter;
float temperature;
float humidity;
float pressure;
public:
WeatherData(){
}
public:
void registerObjecet(Observer* o)
{
observers.push_back(o);
}
void removeObserver(Observer o)
{
for (iter = observers.begin(); iter != observers.end(); ++iter)
{
if (*iter == &o)
{
observers.erase(iter);
break;
}
}
}
void notifyObservers()
{
for(int i = 0; i < observers.size();i++)
{
Observer* observer = observers[i];
observer->update(temperature,humidity,pressure);
}
}
void measurementsChanged()
{
notifyObservers();
}
void setMeasurements(float temperature,float humidity,float pressure)
{
this->temperature = temperature;
this->humidity = humidity;
this->pressure = pressure;
measurementsChanged();
}
};
class CurrentConditionsDisplay : public Observer,public DisplayElement
{
public:
float temperature;
float humidity;
Subject* weatherData;
public:
CurrentConditionsDisplay(Subject* in_weatherData)
{
this->weatherData = http://www.mamicode.com/in_weatherData;
in_weatherData->registerObjecet(/*(Observer*)*/this);
}
void update(float temperature,float humidity,float pressure)
{
this->temperature = temperature;
this->humidity = humidity;
display();
}
void display()
{
printf("Current conditions: %f F degrees and %f %% humidity\n",temperature,humidity);
}
};
//weatherStation
int _tmain(int argc, _TCHAR* argv[])
{
WeatherData* weatherData = http://www.mamicode.com/new WeatherData;
CurrentConditionsDisplay currentDisplay(weatherData);
weatherData->setMeasurements(80,65,30.4f);
weatherData->setMeasurements(82,70,29.2f);
weatherData->setMeasurements(78,90,29.2f);
return 0;
}
设计模式入门,观察者模式,c++代码实现