设计模式:观察者模式(2)C++版

观察者模式:对象之间的一对多关系,当主题变化时,依赖它的对象都会收到通知并自动更新。


C++示例代码如下:

/*
* CONTENTS: DESIGN PATTERN, OBSERVER PATTERN
*   AUTHOR: YAO H. WANG
*     TIME: 2013-10-18 22:47:48
*  EDITION: 1
*
* ALL RIGHTS RESERVED!
*/

#include <list>
#include <iostream>

using namespace std;

class DisplayElement
{
	virtual void display() = 0;
};

//观察者
class Observer
{
public:
	virtual void update(float temperature, float humility, float pressure) = 0;
};

//主题
class Subject
{
public:
	virtual void registerObserver(Observer *ob) = 0;
	virtual void removeObserver(Observer *ob) = 0;
	virtual void notifyObservers() = 0;
};

class CurrentConditionsDisplay: public Observer, public DisplayElement
{
private:
	Subject *su;
	float temperature, humility;

public:
	CurrentConditionsDisplay(Subject *su)
	{
		this->su = su;
		su->registerObserver(this);
	}

	void update(float temperature, float humility, float pressure)
	{
		this->temperature = temperature;
		this->humility = humility;
		display();
	}

	void display()
	{
		cout << "Current Conditions: " << temperature <<
			"F degree and  " << humility << "% humility" << endl;
	}
};

class WeatherData: public Subject
{
private:
	list<Observer*> lo;
	float temperature, humility, pressure;

public:
	WeatherData()
	{
		//Java中此处需要生成ArrayList对象
	}

	void registerObserver(Observer *ob)
	{
		lo.push_back(ob);
	}

	void removeObserver(Observer *ob)
	{
		lo.remove(ob);
	}

	typedef list<Observer*>::const_iterator locit;
	void notifyObservers()
	{
		for(locit l=lo.begin(); l!=lo.end(); ++l)
			(*l)->update(temperature, humility, pressure);
	}

	void measurementsChanged(float temperature, float humility, float pressure)
	{
		this->temperature = temperature;
		this->humility = humility;
		this->pressure = pressure;
		notifyObservers();
	}
};

//测试
void main()
{
	WeatherData *wd = new WeatherData();
	Observer *ob = new CurrentConditionsDisplay(wd);
	wd->measurementsChanged(80, 65, 30.4f);

	delete wd;
	delete ob;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值