观察者模式(状态改变-通知-更新行为)

    所谓观察者模式,便是定义了一种一对多的关系,由多个对象观察一个主题对象,当主题对象的状态发生了变化,这个主题对象会通知所有的观察者。这些观察者会根据通知的情况自动更新自己的状态。

  1.主题纯虚基类。

    m_list:用于保存观察者对象的链表

    Attach接口,用于增添观察者,对象

    Dettach接口,删除观察者对象

    Notify接口,遍历通知所有观察者对象

  2.观察者纯虚基类

    upadate接口,用于更新自己的行为。

 

  在参看一些书籍的时候,提到了观察者模式中经常涉及到推拉模式,推拉模式的概念理解了,不过应用还有些模糊,还希望有朋友给予解答。

  下面是一个班长作为主题类对象,班上篮球队队员和啦啦队队员作为观察者对象的一个模拟场景。

// tEST.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <list> #include <string> using namespace std; class CObserver; //观察者基类 class CSubject { public: CSubject(){}; ~CSubject(){}; //观察者的增添通知者 virtual void Attach( CObserver* sj ) = 0; //观察者移除通知者 virtual void Detach( string name ) = 0; //观察者的通知行为 virtual void Notify( string szAction ) = 0; protected: list< CObserver* > m_subList; }; //被通知者接口 class CObserver { public: CObserver(){}; ~CObserver(){}; CObserver( string szRole, string szAction ):m_szRole(szRole), m_szAction(szAction){}; //更新行为接口 virtual void Update( string szAction ) = 0; //获得当前对象的角色属性 string GetRole(){ return m_szRole; }; protected: string m_szRole; string m_szAction; }; //运动员类,担任的是被通知者的行为 class CPlayer:public CObserver { public: CPlayer(){ m_szRole = "P"; }; ~CPlayer(){}; //被通知者更新行为 virtual void Update( string szAction ); }; void CPlayer::Update( string szAction ) { if ( "lesson" == szAction ) { cout<<"Play Game!"<<endl; } else { cout<<"Play Basketball!"<<endl; } } //拉拉队类,被通知角色 class CCheerGirl:public CObserver { public: CCheerGirl(){ m_szRole = "C"; }; ~CCheerGirl(){}; //更新行为 virtual void Update( string szAction ); }; void CCheerGirl::Update( string szAction ) { if ( "lesson" == szAction ) { cout<<"Go Shopping!"<<endl; } else { cout<<"Cheer Up,Cheer Up!"<<endl; } } //班长类,担任观察者角色 class Monitor:public CSubject { public: Monitor(){}; ~Monitor(){}; virtual void Attach( CObserver* sj ); virtual void Detach( string name ); virtual void Notify( string szAction ); }; //注册被通知者 void Monitor::Attach( CObserver* sj ) { m_subList.push_back( sj ); } //移除被通知者 void Monitor::Detach( string name ) { for ( list< CObserver* >::iterator i = m_subList.begin(); i != m_subList.end(); i++ ) { if ( name == (*i)->GetRole() ) { delete (*i); *i = NULL; m_subList.remove( *i );//?? } } } //通知被通知者的行为,广播的方式 void Monitor::Notify( string szAction ) { for ( list< CObserver* >::iterator i = m_subList.begin(); i != m_subList.end(); i++ ) { (*i)->Update(szAction); } } int main() { CObserver* p1 = new CPlayer; CObserver* p2 = new CPlayer; CObserver* p3 = new CPlayer; CObserver* g1 = new CCheerGirl; CSubject* m = new Monitor; m->Attach(p1); m->Attach(p2); m->Attach(p3); m->Attach(g1); m->Notify("lesson"); m->Notify("Play"); delete p1; delete p2; delete p3; delete g1; delete m; int a = 0; cin>>a; return 0; }

 

你可能感兴趣的:(list,String,delete,iterator,Class,UP)