觀察者模式 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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章