2013年9月13日 星期五

Observer Model example for C++


  • Observer Model
    • The Observer dose not actively to get the data from the Subject else the Subject will
      notify the Observer when there are something changed.
    • 觀察者模式定義了物件之間一對多的關係
    • 主題(Subject) 更新觀察者的方式 ,是透過一個共用介面。
    • 觀察者與可觀察者之間採用鬆綁的方式結合(loose-coupling),因為可觀察者不知道觀察者的細節,只知道觀察者有實踐特定的觀察者介面。




#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <list>

using namespace std;

class CObserver
{
public:
        virtual void update(int data) = 0;
};

class CSubject
{
public:
        virtual void registerObserver(CObserver *obs) = 0;
        virtual void deleteObserver(CObserver *obs) = 0;
        virtual void notify(void) = 0;
};

class CInformationStation : public CSubject
{
private:
        list<CObserver *> m_observerList;
public:
        virtual void registerObserver(CObserver *obs);
        virtual void deleteObserver(CObserver *obs);
        virtual void notify(void);
};

void CInformationStation::registerObserver(CObserver *obs)
{
        list<CObserver *>::iterator it;
        bool found = false;

        for(it = m_observerList.begin(); it != m_observerList.end(); it++) {
                if(*it == obs){
                        found = true;
                        break;
                }
        }

        if(!found)
                m_observerList.push_back(obs);
}

void CInformationStation::deleteObserver(CObserver *obs)
{
        list<CObserver *>::iterator it;

        for(it = m_observerList.begin(); it != m_observerList.end(); it++) {
                if(*it == obs) {
                        m_observerList.erase(it);
                        break;
                }
        }
}

void CInformationStation::notify(void)
{
        list<CObserver *>::iterator it;

        for(it = m_observerList.begin(); it != m_observerList.end(); it++) {
                srand((int)time(0));
                sleep(1);
                (*it)->update( rand() % 1000);
        }
}

class CStatistic : public CObserver
{
private:
        int m_data;
public:
        CStatistic() : m_data(0) {}

        virtual void update(int data)
        {
                m_data = data;
        }

        void display(void)
        {
                printf("[%s] m_data:%d\n", __PRETTY_FUNCTION__, m_data);
        }
};

int main()
{
        CInformationStation station;
        CStatistic statistic1, statistic2, statistic3;

        station.registerObserver(&statistic1);
        station.registerObserver(&statistic2);
        station.registerObserver(&statistic3);

        station.notify();

        statistic1.display();
        statistic2.display();
        statistic3.display();

        return 0;
}

沒有留言:

張貼留言