观察者模式 C++ 实现

#include<iostream>
#include<string>
#include<list>
#include<algorithm>
/*
  气象监控应用问题 (head first 设计模式案例) 
*/ 
using namespace std;

class observer   //观察者公共接口 
{
  public:
         virtual void update(float tmp, float humidity, float pressure) {}    
};

class subject    //主题公共接口     问题:成员函数为什么不能用纯虚函数? 
{ public:
  virtual void register_observer(observer o) {}
  virtual void remove_observer(observer o){}
  virtual void notify_observer() {}
};



class display_element   //显示公共接口 
{
  public:
       virtual void display() = 0;    
};



class weatherdata : public subject   //具体主题 
{
  private:
    float temperature;
    float humidity;
    float pressure;
    list<observer*> *observers;
  public:
    weatherdata()
    {
      observers = new list<observer*>;    
    }
    void register_observer(observer* o)  //将观察者注册到观察者列表中 
    {
      (*observers).push_back(o);   
    }
    void remove_observer(observer* o)
    { list<observer*>::iterator it;
      it = find((*observers).begin(),(*observers).end(),o);
       
      (*observers).erase(it);    
    }
    void notify_observer()     //通知观察者 
    { list<observer*>::iterator ite;
      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: " <<temperature<< endl;
         cout <<"humidity:" <<humidity<< endl;
         cout <<"pressure:" << pressure<< endl;    
       }
      
};

//  客户端  
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;    
}


 

 

总结:比较常用的设计模式 MVC就是用的这个模式。还需要好好理解。

发布了53 篇原创文章 · 获赞 5 · 访问量 5万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章