哪位高手能帮我用C++写一个观察者模式的程序?感激不尽!!!

急用!谢谢!... 急用!谢谢! 展开
 我来答
feldspar
2007-12-11 · TA获得超过384个赞
知道小有建树答主
回答量:564
采纳率:0%
帮助的人:0
展开全部
#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 Client : 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 _tmain(int argc, _TCHAR* argv[])
{
Window w;
Client c;
w.attachObserver(&c);

Button btn;
w.attachObserver(&btn);

w.OnSize(50, 20);

return 0;
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式