- 观察者模式属于行为型模式中的一种,其作用是当一个对象的状态发生改变时,能够通知其他关联对象,自动刷新对象的状态,有点像马路上的车和红绿灯的关系,当红灯这个对象亮起的时候,小车应该是停下来的状态,在小灯变绿的时候,小车才是行驶的状态。小车里面的人监听灯的变化情况。
- Talk is cheap(具体实现代码如下)
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Traffic_light;
class People_car
{
public:
People_car(string name, Traffic_light *light)
{
m_name = name;
Light_state = light;
}
void update(string action)
{
cout << "Got it:" << action << endl;
}
private:
string m_name;
Traffic_light *Light_state;
};
class Traffic_light
{
public:
void addObserver(People_car *o)
{
v.push_back(o);
}
void Notify(string action)
{
for (vector<People_car *>::iterator it= v.begin(); it!=v.end(); it++ )
{
(*it)->update(action);
}
}
void setAction(string action)
{
m_action = action;
Notify(m_action);
}
private:
string m_action;
vector<People_car *> v;
};
int main()
{
Traffic_light *s1 = new Traffic_light;
People_car *po1 = new People_car("A", s1);
s1->addObserver(po1);
s1->setAction("red light");
s1->setAction("green light");
return 0;
}