2、观察者类需要继承自Observer,并且重写了update()函数,在该函数中判断,如果发生的事件是自己期望的,update()函数就会被调用。
示例代码如下:
class Test1 : public Observer { public: //observer virtual void update(Observable* from, YtEvent *e) { if(NULL == e) return; std::string szEvent = e->getEvent(); if(szEvent == "start_update") { printf("I find a Update Message.\n"); } } }; |
3、被观察者类需要继承自Observable,其中定义了一个value变量,需要实现的是,如果value发生变化,那么通知Test1类知道。
示例代码如下:
#ifndef __DOC_DATA_ #define __DOC_DATA_ #include "Observer.h" class CDoc : public Observable { public: CDoc() { value = 0; } ~CDoc() { value = -1; } void setValue(int arg) { value= arg; } int getValue() { return value; } private: int value; }; #endif |
4、被监视的类CDoc,调用addObserver()函数添加观察者类(函数参数要进行转换),定义某事件,把发生该事件的消息通过调用notifyObservers()函数通知观察者类
测试代码如下:
// ObserverTest.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "Observer.h" #include "Test1.h" #include "DocData.h" #include "YtEvent.h" void main() { CDoc data; TestOBSERVER1 test; char aa[128]; data.addObserver(static_cast<Observer*>(&test)); YtEvent yet("start_update"); data.notifyObservers(&yet); printf("aaaaaaaaaaaaaaaaaaaaaaa\n"); scanf("%s", aa); } |
5、结束