现在的位置: 首页 > 综合 > 正文

观察者模式(Subject/Observer)

2019年05月13日 ⁄ 综合 ⁄ 共 2134字 ⁄ 字号 评论关闭


定义:对象间的一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。 

功能:搜索数据库,当有需要公布的数据将其用各种方式发送出去。
 
观察者模式无疑能很好的做到上面的要求,无论要多少种方式,只要增加多个继承之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 
*= *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;
        }


}
转贴 http://www.cppblog.com/YGFaith/archive/2008/08/29/60363.html
【上篇】
【下篇】

抱歉!评论已关闭.