observer.cpp

来自「在Windows和VxWorks平台下,观察者模式C++实用实现.」· C++ 代码 · 共 129 行

CPP
129
字号
////////////////////////////////////////////////
// Filename: Observer.cpp
// Function: 
// Author: ShaoxiongLi
// Date: 2008年8月28日
// Project: xxxMain
// Remarks:  	  
// History:  	 
////////////////////////////////////////////////



#include "stdafx.h"
#include "Observer.h"
#include "Subject.h"



// 构造函数
Observer::Observer( void ) : m_subjects( NULL )
{
	m_subjects = new SubjectList( );
}



// 拷贝构造函数
Observer::Observer( const Observer & rhsObserver ) : m_subjects( NULL )
{
	m_subjects = new SubjectList( );
}



// 析构函数
Observer::~Observer( void )
{
	list< Subject * >::iterator it;	
	
	if ( !m_subjects->empty( ) ) 
	{
		for ( it = m_subjects->begin( ); it != m_subjects->end( ); it++ )
		{
			(*it)->Detach( *this );
		}
	}

	delete m_subjects;
}



// 更新通知
void Observer::Update( const Subject & subject, char * message, int msgLen )
{

}



// 定时器事件
//void Observer::OnTimer( const Subject & subject, int nTimer )
//{
//}



// 目标对象变化通知
void Observer::SubjectNotify( Subject & subject ) 
{
	if ( &subject != NULL ) 
	{
		m_subjects->push_back( &subject );		
	}
}



// 目标对象释构
void Observer::SubjectDestructe( Subject & subject )
{
	m_subjects->remove( &subject );
}



// 目标对象是否存在
bool Observer::ExistSubject( Subject & subject )
{
	list< Subject * >::iterator it;
	bool bFound = FALSE;
	bool bContinueSearch = FALSE;

	bFound = FALSE;

	if ( !m_subjects->empty( ) )
	{
		bContinueSearch = FALSE;
	}
	else
	{
		bContinueSearch = TRUE;
	}

	it = m_subjects->begin( );	

	// 查找目标对象
	while ( bContinueSearch == TRUE )
	{
		if ((*it) == &subject )
		{
			// 对象已存在 
			bContinueSearch = FALSE;
			bFound = TRUE;
		}
		else
		{
			it++;
			if ( it == m_subjects->end( ) )
			{
				// 查找完毕,对象不存在
				bContinueSearch = FALSE;
			}	
		}
	}

	return bFound;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?