开发学院软件开发C++ 观察者模式(Subject/Observer) 阅读

观察者模式(Subject/Observer)

 2010-10-15 09:07:55 来源:Web开发网   
核心提示://接口//ITransfer.h#pragma onceclass ITransfer{public:virtual bool DoTransfer(...) = 0;};//FetionTransfer.h#pragma once #include "Transfer.h"class CFeti

//接口
//ITransfer.h
#pragma once

class ITransfer
{
public:
  virtual bool DoTransfer(...) = 0;
};

//FetionTransfer.h
#pragma once
  #include "Transfer.h"
class CFetionTransfer:public ITransfer
{
public:
  CFetionTransfer();
  ~CFetionTransfer();
  bool DoTransfer(...);
private:
  ......
};

//MailTransfer.h
#pragma once
  #include "Transfer.h"
class CMailTransfer: public ITransfer
{
public:
  CMailTransfer();
   ~CMailTransfer();
  bool DoTransfer(...);
private:
....
};

//TransferPool.h
#pragma once

#include "Transfer.h"
#include <vector>
using namespace std;

class CTransferPool
{
private:
  vector<ITransfer*> vo;
public:
  virtual ~CTransferPool();

  void Login(ITransfer* po);

  void Logout(ITransfer* po);
  //向各成员广播消息
  void Notify(...);
};

//TransferPool.cpp
#include "TransferPool.h"

CTransferPool::~CTransferPool()
{
  vector<ITransfer*>::iterator vi = vo.begin();
  for (; vi != vo.end(); vi++)
  {
         if(*vi)
          {
            delete *vi;
             *vi = NULL;
          }
  }
}

void CTransferPool::Login(ITransfer* po)
{
  vo.push_back(po);
}

void CTransferPool::Logout(ITransfer* po)
{
  vector<ITransfer*>::iterator vi = vo.begin();
  for (; vi != vo.end(); vi++)
  {
    if (*vi == po)
      vo.erase(vi);
  }
}

void CTransferPool::Notify(...)
{
  vector<ITransfer*>::iterator vi = vo.begin();
  for (; vi != vo.end(); vi++)
  {
    ITransfer *s = *vi;

    (*vi)->DoTransfer(...);
  }
}

void main
{
  CTransferPool*m_pTranPool= new CTransferPool();

  CFetionTransfer *m_pFetionTran = new CFetionTransfer(...);
  CMailTransfer *m_pMailTran = new CMailTransfer(...);

  m_pTranPool->Login(m_pFetionTran);
  m_pTranPool->Login(m_pMailTran);

    while(需要发送消息)
    {
      m_pTranPool->Notify();
    }

    //释放
     if(m_pTranPool)
    {
      delete m_pTranPool;
      m_pTranPool = NULL;
    }

}

上一页  1 2 

Tags:观察者 模式 Subject

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接