#include <iostream>
#include <list>
using namespace std;
/*
观察者模式,当一个对象的改变需要同时改变其他对象,并且不知道有多少对象需要改变
主要工作在于解除耦合,让双方都依赖于抽象,而不是依赖于具体,使得各自的变化都不
会影响另一边的变化
*/
class Observer {
public:
virtual void Update() =
0;
};
class Subject {
private:
list<Observer*>
m_pObservers;
public:
void Attach(Observer*
pObserver)
{
m_pObservers.push_back(pObserver);
}
void Detach(Observer*
pObserver)
{
m_pObservers.remove(pObserver);
}
void Notify()
{
list<Observer*>::iterator iter =
m_pObservers.begin();
while (iter !=
m_pObservers.end())
{
Observer* p = (Observer*)(*
iter);
p->
Update();
iter++
;
}
}
};
class ConcreteSubject :
public Subject {
public:
string m_subjectState;
};
class ConcreteObserver :
public Observer {
public:
string m_name;
string m_observerState;
ConcreteSubject*
m_pSubject;
public:
ConcreteObserver(ConcreteSubject* pSubject,
string name)
{
m_pSubject =
pSubject;
m_name =
name;
}
void Update()
{
m_observerState = m_pSubject->
m_subjectState;
printf("%s %s\n",m_name.c_str(),m_observerState.c_str());
}
};
int main()
{
ConcreteSubject* s =
new ConcreteSubject();
s->Attach(
new ConcreteObserver(s,
"x"));
s->Attach(
new ConcreteObserver(s,
"y"));
s->Attach(
new ConcreteObserver(s,
"z"));
s->m_subjectState =
"abc";
s->
Notify();
return 0;
}
转载于:https://www.cnblogs.com/yanjiu/archive/2012/08/10/2631404.html
相关资源:数据结构—成绩单生成器