{
observers = new list
}
void register_observer(observer* o) //将观察者注册到观察者列表中
{
(*observers).push_back(o);
}
void remove_observer(observer* o)
{ list
it = find((*observers).begin(),(*observers).end(),o);
(*observers).erase(it);
}
void notify_observer() //通知观察者
{ list
ite = observers->begin();
for(; ite != observers->end(); ite++)
{
(*ite)->update(temperature,humidity,pressure);
}
}
void set_measurements(float temperature, float humidity, float pressure)
{
this->temperature = temperature;
this->humidity = humidity;
this->pressure = pressure;
notify_observer(); //更新了随时通知观察者
}
};
class currentconditiondisplay: public observer, public display_element //具体观察者 ,同时继承了显示公共接口
{
private:
float temperature;
float humidity;
float pressure;
weatherdata *weatherstation;
public:
currentconditiondisplay(weatherdata *weatherstation)
{
this->weatherstation = weatherstation;
weatherstation->register_observer(this); //是不是因为继承了observer接口才能注册?
}
void update(float temperature, float humidity, float pressure)
{
this->temperature = temperature;
this->humidity = humidity;
this->pressure = pressure;
display();
}
void display()
{
cout <<"current condition: "<< endl;
cout <<"temperature: " <
}
};
// 客户端
int main()
{
weatherdata *weather_station = new weatherdata(); // 用new时,一定要记住返回的是指针!
currentconditiondisplay *display = new currentconditiondisplay(weather_station);
weather_station->set_measurements(89.67,33.56,56.98);
weather_station->set_measurements(11,34.01,39);
system("pause");
return 0;
}