观察者模式代码

#pragma warning(disable: 4786)


#include <iostream>
#include <set>
using namespace std;

/*
¹Û²ìÕßģʽ£º ¹Û²ìÕߣ¨Ê¼þÏìÓ¦Õߣ©-----Ö÷Ì壨ʼþ·¢ÉúÕߣ©---ÈÝÆ÷£¨±£´æ¶ÔÖ÷Ìå¸ÐÐËȤµÄ¹Û²ìÕߣ©

*/
class IObserver
{
public:
 virtual void Reflect(int id)=0;
protected:
private:
};

class CObserver1:public IObserver
{
public:
 void Reflect(int id)
 {
  switch(id)
  {
  case -1:
   cout<<"CObserver1:i reflect to .sb. the event happened is id ==-1/n";
   break;
  case 0:
   cout<<"CObserver1:i reflect to .sb. the event happened is id ==0 /n";
      break;
  default:
   cout<<"CObserver1:i reflect to .sb. the event that i instreasted happended /n";
      break;
  }
 }
protected:
private:
};
class CObserver2:public IObserver
{
public:
 void Reflect(int id)
 {
  switch(id)
  {
  case -1:
   cout<<"CObserver2:i reflect to .sb. the event happened is id ==-1/n";
   break;
  case 0:
   cout<<"CObserver2:i reflect to .sb. the event happened is id ==0 /n";
   break;
  default:
   cout<<"CObserver2:i reflect to .sb. the event that i am not instreasted happended /n";
   break;
  }
 }
protected:
private:
};

class CObserverable
{
public:
 bool Register( IObserver * pob)
 {
  m_obs.insert( pob );
  return true;
 }
 bool UnRegister( IObserver * pob )
 {
  m_obs.erase(pob);
  return true;
 }
protected:

 set<IObserver*> m_obs;
private:
};

class CObserverableImpl:public CObserverable
{
public:
 void Set(int i)
 {
  m_i = i;
  set<IObserver*>::iterator itb,ite;
  itb = m_obs.begin();
  ite = m_obs.end();
  for( ; itb!= ite ;++itb )
  {
   (*itb)->Reflect(i);
  }
 }
protected:
private:
 int m_i ;
};
int main(int argc, char* argv[])
{
 CObserver1 ob1;
 CObserver2 ob2;
 CObserverableImpl im;
 im.Register( &ob1 );
 im.Register( &ob2 );
 im.Set( 2 );
 im.Set( 0 );
 im.Set( -1 );
 im.UnRegister( &ob1);
 im.UnRegister( &ob2 );
 return 0;
}
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值