design_pattern_observer

本文详细阐述了如何在HeadFirstDesignPattern中实现观察者模式,通过具体实例展示了如何定义主体类、观察者类及其具体实现,以及如何在天气站问题中应用这一模式。

This post implements observer pattern in <Head First Design Pattern>. Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. The basic structure is given by

We need to implement main four classes,

1. First is the subject abstract class. Subject manages Observers, add, remove observers and update information.

2. Then we have Observer abstract class. The basic function for observer class is to receive and update information.

3. ConcreteObserver inherits from Observer, except for receive and update information, it defines some specific method to deal with information.

4. ConcretSubject inherits from Subject, doing add, remove, update, and other stuffs, is an integral work interface(station).

class Subject {
public:
    virtual void registerObserver(Observer* o) = 0;
    virtual void removeObserver(Observer* o) = 0;
    virtual void notifyObserver() = 0;
};

class Observer{
public:
    virtual void update(double temp, double humidity, double pressure) const = 0;
};

Specifically, for weather station problem in the book, we have class structure

Weather Data implements the subject abstract class. Its responsibility is to manage observers,  which are CurrentConditions, StatsitcsDisply and ThirdPartyDisplay.

class WeatherData : public Subject{
public:
    WeatherData(){
        this->temperature = 0;
        this->humidity = 0;
        this->pressure = 0;
    }

    WeatherData(double temp, double humid, double pres){
        this->temperature = temp;
        this->humidity = humid;
        this->pressure = pres;
    }

    ~WeatherData(){
        for(std::list<Observer*>::iterator it=observers.begin;observers.end() != it; ++it){
            delete *it;
            *it = NULL;
        }
    }

    virtual void registerObserver(Observer* o) {
		observers.push_back(o);
	}

	virtual void removeObserver(Observer* o) {
		observers.remove(o);
	}

    virtual void notifyObservers() {
		for (std::list<Observer*>::iterator it = observers.begin(); observers.end() != it; ++it) {
			Observer* observer = *it;
			observer->update(temperature, humidity, pressure);
		}
	}

	virtual void measurementsChanged() {
		notifyObservers();
	}

	virtual void setMeasurements(double temperature, double humidity, double pressure) {
		this->temperature = temperature;
		this->humidity = humidity;
		this->pressure = pressure;
		measurementsChanged();
	}

	virtual float getTemperature() {
		return temperature;
	}
	virtual float getHumidity() {
		return humidity;
	}
	virtual float getPressure() {
		return pressure;
	}

protected:
    double temperature;
	double humidity;
	double pressure;
	static std::list<Observer*> observers;
};

The WeatherData contains basic data and information of a list of observers. It can add and remove them. The list should be static?  We further implement one Observer instance, CurrentConditionsDisplay.

class CurrentConditionDisplay : public Observer{
public:
    CurrentConditionDisplay(){
        temperature = 0;
        humidity = 0;
        pressure = 0;
        //weatherdata = NULL;
    }

    CurrentConditionDisplay(Subject* wd){
        this->weatherdata = wd;
        weatherdata->registerObserver(this);
    }

    ~CurrentConditionDisplay(){
        delete weatherdata;
        weatherdata = NULL;
    }

    virtual void update(double temp, double humid, double pres) {
		this->temperature = temp;
		this->humidity = humid;
		this->pressure = pres;
		this->display();
	}

	void display(){
        std::cout << "Temperature|Humidity|Pressure:" << temperature << "|" << humidity  << "|"               << pressure << std::endl;
	}

private:
    double temperature;
    double humidity;
	double pressure;
	Subject* weatherdata;
};
main function is given by

#include <iostream>
#include <list>
#include <./weatherstation.hpp>

int main()
{
    WeatherData* wd = new WeatherData();

    CurrentConditionDisplay* cd = new CurrentConditionDisplay(wd);

    wd->setMeasurements(80, 65, 30);
    wd->setMeasurements(82, 62, 29);
    wd->setMeasurements(79, 60, 31);

    return 0;
}
The result is




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值