观察者模式--观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使他们能够自动更新自己。
// observer.cpp : 定义控制台应用程序的入口点。
#include<iostream>
#include<list>
#include<string> //vs2005要包含这个头文件
using namespace std;
class Observer;
class Subject
{
public:
virtual void notify()=0;
virtual void attach(Observer *o)=0;
virtual void detach(Observer *o)=0;
string getState()
{
return state;
}
void setState(string s)
{
state = s;
}
protected:
string state;
list<Observer*> l;
};
class Observer
{
public:
virtual void update(Subject *s)
{
cout << "Observer::update" << endl;
}
};
class ConcreteSubject:public Subject
{
public:
virtual void notify()
{
list<Observer*>::iterator it = l.begin();
while(it != l.end())
{
(*it)->update(this);
it++;
}
}
virtual void attach(Observer *o)
{
l.push_back(o);
}
virtual void detach(Observer *o)
{
l.remove(o);
}
};
class Observer1:public Observer
{
public:
virtual void update(Subject *s)
{
cout << "Observer1::update Subject's state is " << s->getState() << endl;
}
};
class Observer2:public Observer
{
public:
virtual void update(Subject *s)
{
cout << "Observer2::update Subject's state is " << s->getState() << endl;
}
};
int main()
{
Observer1 o1;
Observer2 o2;
ConcreteSubject cs;
cs.attach(&o1);
cs.attach(&o2);
cs.setState("state1");
cs.notify();
cs.setState("state2");
cs.notify();
return 0;
}