关于C++观察者模型的学习和理解

  1. 观察者模式属于行为型模式中的一种,其作用是当一个对象的状态发生改变时,能够通知其他关联对象,自动刷新对象的状态,有点像马路上的车和红绿灯的关系,当红灯这个对象亮起的时候,小车应该是停下来的状态,在小灯变绿的时候,小车才是行驶的状态。小车里面的人监听灯的变化情况。
  2. 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值