在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
#include <string> #include <iostream> #include <set> class IObserver; class ISubject { public: virtual void registerObserver(IObserver * o) = 0; virtual void removeObserver(IObserver * o) = 0; virtual void notifyObservers() = 0; }; class IObserver { protected: IObserver(){}; public: virtual void update(float temp, float humidity, float pressure) = 0; }; class IDisplayElement { protected: IDisplayElement(){}; public: virtual void display() = 0; }; typedef std::set<IObserver *> ObserverList; typedef std::set<IObserver *>::iterator ObserverListIter; class WeatherData: public ISubject { private: ObserverList m_Oberservers; float m_temp; float m_humidity; float m_pressure; public: WeatherData () {}; ~WeatherData () {}; virtual void registerObserver(IObserver * o) { m_Oberservers.insert(o); } virtual void removeObserver(IObserver * o) { ObserverListIter iter = m_Oberservers.find(o); if (iter!=m_Oberservers.end()) { m_Oberservers.erase(iter); } } virtual void notifyObservers() { ObserverListIter iter = m_Oberservers.begin(); for (;iter!=m_Oberservers.end();iter ++ ) { // notify All Observers IObserver * pObserver = static_cast<IObserver *>(* iter); pObserver->update(m_temp,m_humidity,m_pressure); } } void measurementsChanged() { notifyObservers(); } void setMeasurements(float temp, float humidity, float pressure) { m_temp = temp; m_humidity = humidity; m_pressure = pressure; measurementsChanged(); } }; class CurrentConditionsDisplay:public IObserver,public IDisplayElement { float m_temp; float m_humidity; ISubject *m_WeatherData; public: virtual void update(float temp, float humidity, float pressure) { m_temp = temp; m_humidity = humidity; display(); } virtual void display() { std::cout << "Current Conditions:" << m_temp << "," << m_humidity <<std::endl; } }; class CurrentConditionsDisplay2:public IObserver,public IDisplayElement { float m_temp; float m_humidity; float m_pressure; public: virtual void update(float temp, float humidity, float pressure) { m_temp = temp; m_humidity = humidity; m_pressure = pressure; display(); } virtual void display() { std::cout << "Current Conditions2:" << m_temp << "," << m_humidity << "," << m_pressure <<std::endl; } }; int main() { CurrentConditionsDisplay * display1 = new CurrentConditionsDisplay(); CurrentConditionsDisplay2 * display2 = new CurrentConditionsDisplay2(); WeatherData * data = new WeatherData(); data->registerObserver( display1); data->registerObserver (display2); data->setMeasurements(100,0,200); data->setMeasurements(50,50,500); data->removeObserver(display1); data->setMeasurements(10,10,10); getchar(); return 0; }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论