#include#include#includeusingnamespacestd;/////////////////////抽象模式定义classCObservable;//观察者,纯虚基类classCObserver{public:CObserver::CObserver(){};virtualCObserver::~CObserver(){};//当被观察的目标发生变化时,通知调用该方法//来自被观察者pObs,扩展参数为pArgvirtualvoidUpdate(CObservable*pObs,void*pArg=NULL)=0;};//被观察者,即SubjectclassCObservable{public:CObservable():m_bChanged(false){};virtual~CObservable(){};//注册观察者voidAttach(CObserver*pObs);//注销观察者voidDetach(CObserver*pObs);//注销所有观察者voidDetachAll();//若状态变化,则遍历观察者,逐个通知更新voidNotify(void*pArg=NULL);//测试目标状态是否变化boolHasChanged();//获取观察者数量intGetObserversCount();protected://设置状态变化!!!必须继承CObservable才能设置目标状态voidSetChanged();//初始化目标为未变化状态voidClearChanged();private:boolm_bChanged;//状态setm_setObs;//set保证目标唯一性};/////////////////////抽象模式实现voidCObservable::Attach(CObserver*pObs){if(!pObs)return;m_setObs.insert(pObs);}voidCObservable::Detach(CObserver*pObs){if(!pObs)return;m_setObs.erase(pObs);}voidCObservable::DetachAll(){m_setObs.clear();}voidCObservable::SetChanged(){m_bChanged=true;}voidCObservable::ClearChanged(){m_bChanged=false;}boolCObservable::HasChanged(){returnm_bChanged;}intCObservable::GetObserversCount(){returnm_setObs.size();}voidCObservable::Notify(void*pArg){if(!HasChanged())return;cout::iteratoritr=m_setObs.begin();for(;itr!=m_setObs.end();itr++){(*itr)->Update(this,pArg);}}/////////////////////具体应用类定义和实现//bloger是发布者,即被观察者(subject)classCBloger:publicCObservable{public:voidPublish(conststring&strContent){cout(strContent.c_str()));}};//portal是发布者,即被观察者(subject)classCPortal:publicCObservable{public:voidPublish(conststring&strContent){cout(strContent.c_str()));}};//RSS阅读器,观察者classCRSSReader:publicCObserver{public:CRSSReader(conststring&strName):m_strName(strName){}virtualvoidUpdate(CObservable*pObs,void*pArg=NULL){char*pContent=static_cast(pArg);//观察多个目标if(dynamic_cast(pObs)){cout(pObs)){cout(pArg);if(dynamic_cast(pObs)){cout(pObs)){coutAttach(pRssReader);//bloger注册观察者pBloger->Attach(pMailReader);//bloger注册观察者pPortal->Attach(pRssReader);//portal注册观察者pPortal->Attach(pMailReader);//portal注册观察者//博客发布信息pBloger->Publish(博客分享设计模式);coutPublish(门户分享设计模式);coutDetach(pMailReader);coutGetObserversCount()Publish(门户分享设计模式);system(pause);return0;}