C++:设计模式之观察者模式(例子)

// 设计模式测试.cpp : 定义控制台应用程序的入口点。
// 观察者模式

#include "stdafx.h"
#include 
#include 
#include 
#include 

using namespace std;
/*************************观察者模式之气象布告板示例*********************************/
//观察者接口
class I_Observer
{
public:
	virtual void update(float temperature, float humidity, float pressure) = 0;
};
//展示接口
class IDisplayElement
{
public:
	virtual void display() = 0;
};
//主题接口
class I_Subject
{
public:
	virtual void registerObserver(I_Observer *o)=0;
	virtual void removeObserver(I_Observer *o) = 0;
	virtual void notifyObserver() = 0;
};
class WeatherData : public I_Subject
{
	list observers;
	float temperature;
	float humidity;
	float pressure;
public:
	WeatherData() {
		
	}
	void registerObserver(I_Observer *o) {
		observers.push_back(o);
	}
	void removeObserver(I_Observer *o) {
		list::iterator iter = observers.begin();
		while (iter != observers.end())
		{
			if ((*iter) == o)
			{
				observers.erase(iter);
			}
			++iter;
		}
	}
	void notifyObserver() {
		list::iterator iter = observers.begin();
		while (iter != observers.end())
		{
			(*iter)->update(temperature,humidity,pressure);
			++iter;
		}
	}
	void measurementsChanged() {
		notifyObserver();
	}
	void setMeasurements(float temperature, float humidity, float pressure) {
		this->temperature = temperature;
		this->humidity = humidity;
		this->pressure = pressure;
		measurementsChanged();
	}
};
//布告板
class CurrentConditionsDisplay:public I_Observer, public IDisplayElement
{
	float temperature;
	float humidity;
	I_Subject *weatherData;
public:
	CurrentConditionsDisplay(I_Subject *weatherData) {
		this->weatherData = weatherData;
		weatherData->registerObserver(this);
	}
	void update(float temperature, float humidity, float pressure) {
		this->temperature = temperature;
		this->humidity = humidity;
		display();
	}
	void display () {
		cout << "Current Conditions:" + to_string(this->temperature) + "F degree and " + to_string(this->humidity) + "% humidity"<weatherData = weatherData;
		weatherData->registerObserver(this);
	}
	void update(float temperature, float humidity, float pressure) {
		this->temperature = temperature;
		this->pressure = pressure;
		display();
	}
	void display() {
		cout << "Forecast Conditions:" + to_string(this->temperature) + "F degree and " + to_string(this->pressure) + "— pressure" << endl;
	}
};
//主函数
int main()
{	
	WeatherData *weatherData = new WeatherData();
	CurrentConditionsDisplay *currentDisplay = new CurrentConditionsDisplay(weatherData);
	weatherData->setMeasurements(88,65,40);
	ForecastConditionsDisplay *forecastDisplay = new ForecastConditionsDisplay(weatherData);
	weatherData->setMeasurements(78, 55, 50);
	weatherData->setMeasurements(98, 75, 20);

	system("Pause");
	return 0;
}

你可能感兴趣的:(C++)