#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;
}