定義:對象間的一對多的依賴關系,當一個對象的狀態發生改變時,所有依賴於它的對象都得到通知並被自動更新。
功能:搜索數據庫,當有需要公布的數據將其用各種方式發送出去。
觀察者模式無疑能很好的做到上面的要求,無論要多少種方式,只要增加多個繼承之ITransfer接口的派生類即可,有很好的維護性。
以下是實際的應用.
//接口
//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;
}
}