c++设计模式之观察者模式

时间:2022-09-18 08:28:04

概念:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。

通常讲就是被观察者向左右观察对象通知其状态的改变,以使得观察者进行相应信息的更新。

代码如下

#include

class ObjectUser;//被观察者对象
class Observer
{
protected:
ObjectUser *m_ObjectUser; public:
virtual void NotifyMessage() = ;
}; class Observer1:public Observer
{
Observer1(ObjectUser *g_ObjectUser)
{
m_ObjectUser = g_ObjectUser;
}
public:
virtual void NotifyMessage()
{
int cmd = m_ObjectUser->command;
cout << "被观察者命令改变为"<<cmd;
}
}; class Observer2:public Observer
{
Observer2(ObjectUser *g_ObjectUser)
{
m_ObjectUser = g_ObjectUser;
}
public:
virtual void NotifyMessage()
{
cout << "被观察者通知消息给我说它发生了改变,要我更新";
//.........
}
}; class ObjectUser
{
friend class Observer;
protected:
int command; std::vector<Observer*> ObserverList; public:
void AddObserver(Observer* pUser)
{
ObserverList.push_back(pUser);
} void NotifyMsg()
{
for (int i = ;i<ObserverList.size();i++ )
{
ObserverList[i]->NotifyMessage();
}
}
}; void main()
{
ObjectUser *OUser = new ObjectUser();
Observer pOb1 = new Observer1(OUser);
Observer pOb2 = new Observer2(OUser); OUser->AddObserver(pOb1);
OUser->AddObserver(pOb2);
OUser->NotifyMsg(); }