这两天做MVC,其中有OBSERVER模式的应用,简单实现了下接口。

Subject.h

#ifndef _SUBJECT_H
#define _SUBJECT_H

#include "Observer.h"
#define MAX_OBSERVER_NUM 10

class Subject
{
      public:
             virtual ~Subject();
             virtual void Attach(Observer *pObserver);
             virtual void Detach(Observer *pObserver);      // 未实现
             virtual void Notify();
      protected:
                Subject(int m = MAX_OBSERVER_NUM);
      private:
              Observer **ppObserver;
              int max;
              int size;
};

#endif

Subject.cpp

#include "Subject.h"

Subject::Subject(int m) : max(m), size(0)
{
      ppObserver = new Observer*[max];
}

Subject::~Subject()
{
      if(ppObserver)
             delete [] ppObserver;
}

void Subject::Attach(Observer *pObserver)
{
     if(size >= max)
             return;
     ppObserver[size++] = pObserver;
}

void Subject::Detach(Observer *pObserver)
{
     return;
}

void Subject::Notify()
{
     for(int i = 0; i < size; i++)
             ppObserver[i]->Update(this);
}

Observer.h

#ifndef _OBSERVER_H
#define _OBSERVER_H

class Subject;     // Subject的向前声明

class Observer
{
      public:
             virtual ~Observer() {};
             virtual void Update(Subject* pSubject) = 0;    // 子类必须实现的方法
      protected:
                Observer() {};               // 仅由子类调用
};

#endif