文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>设计模式之观察者(Observer)模式C++实现

设计模式之观察者(Observer)模式C++实现

时间:2010-06-01  来源:jhluroom

#include "stdafx.h"
#include <set>

class Observer;

class Subject
{
    public:
     virtual void attachObserver(Observer* o) = 0;
     virtual void detachObserver(Observer* o) = 0;
     virtual void notify() = 0;
};

class Observer
{
    public:
     virtual void update(Subject* s) = 0;
};

class Window : public Subject
{
    public:
     void attachObserver(Observer* o)
     {
          mObservers.insert(o);
     }

     void detachObserver(Observer* o)
     {
         mObservers.erase(o);
     }

     void notify()
     {
         for (std::set<Observer*>::const_iterator it = mObservers.begin();
         it!=mObservers.end();
         ++it)
         {
         (*it)->update(this);
         }
     }

     void OnSize(int w, int h)
     {
     mWidth = w;
     mHeight = h;
     notify();
     }

     void GetSize(int &w, int &h)
     {
     w = mWidth;
     h = mHeight;
     }

    protected:
     std::set<Observer*> mObservers;
     int mWidth, mHeight;
};

class Lable : public Observer
{
    public:
     void update(Subject* s)
     {
         int w, h;
         Window* pWnd = (Window*)s;
         pWnd->GetSize(w, h);

         mWidth = w / 2;
         mHeight = h / 2;
     }

    private:
     int mWidth, mHeight;
};

class Button : public Observer
{
    public:
     void update(Subject* s)
     {
         int w, h;
         Window* pWnd = (Window*)s;
         pWnd->GetSize(w, h);

         mWidth = w / 8;
         mHeight = h / 8;
     }

    private:
     int mWidth, mHeight;
};

int main(int argc, _TCHAR* argv[])
{
     Window w;
     Lable lab;
     w.attachObserver(&lab);

     Button btn;
     w.attachObserver(&btn);

     w.OnSize(50, 20);

     return 0;
}


相关阅读 更多 +
排行榜 更多 +
别惹神枪手安卓版

别惹神枪手安卓版

冒险解谜 下载
坦克战争世界

坦克战争世界

模拟经营 下载
丛林反击战

丛林反击战

飞行射击 下载