您的位置:首页 > 其它

使用list实现一个简单的Listener管理

2006-07-05 15:12 846 查看
使用list来完成一个简单的listener管理类,当增加和删除操作不频繁的时候,可以考虑用vector来代替list,提高效率。这个简单管理类有很多的设计不足,它的存在主要目的是让网友知道如何使用list,而非是如何设计listener管理类。
#include <iostream>
#include <algorithm>
#include <functional>
#include <list>
#include <assert.h>

using namespace std;

class IListener
{
public:
virtual ~IListener(){}
virtual void notify( void *usrArg ) = 0;
};

class IListenerManager: public IListener
{
public:
virtual ~IListenerManager(){}
virtual bool addListener( IListener *pListener ) = 0;
virtual bool removeListener( IListener *pListener ) = 0;
virtual void notify( void *usrArg ) = 0;
};

class WYQListenerManager: public IListenerManager
{
typedef list<IListener*>::iterator ListIterator;

list<IListener*> manager;

// Disable copying constructor and assigning operation
WYQListenerManager( const WYQListenerManager &rhs );
WYQListenerManager& operator=( const WYQListenerManager& rhs );

struct SNotify: public binary_function<IListener*, void*, bool>
{
inline bool operator()( IListener *pListener, void *usrArg ) const
{
assert( pListener != NULL );
pListener->notify( usrArg );

return true;
}
};

struct SDeleter: public unary_function<IListener*, void>
{
inline void operator()( IListener *pListener ) const
{
assert( pListener != NULL );
delete pListener;
}
};

void cleanup()
{
for_each( manager.begin(), manager.end(), SDeleter() );
}

public:
WYQListenerManager() : manager()
{
cout << "Construct WYQListener" << endl;
}

virtual ~WYQListenerManager()
{
cleanup();
cout << "Destruct WYQListener" << endl;
}

virtual bool addListener( IListener *pListener )
{
assert( pListener != NULL );
if ( pListener == NULL )
return false;

//if ( find( manager.begin(), manager.end(), pListener ) == manager.end() )
// return false;
assert ( find( manager.begin(), manager.end(), pListener ) == manager.end() );
manager.push_back( pListener );

return true;
}

virtual bool removeListener( IListener *pListener )
{
assert( pListener != NULL );
if ( pListener == NULL )
return false;

ListIterator it = find( manager.begin(), manager.end(), pListener );

if ( it == manager.end() )
return false;

manager.erase( it );

return true;
}

virtual void notify( void *usrArg )
{
for_each( manager.begin(), manager.end(), bind2nd( SNotify(), usrArg ) );
}
};

class WYQListener: public IListener
{
int id;

public:
WYQListener( int _id = 0 ) : id( _id )
{
cout << "Construct WYQListener" << endl;
}

virtual ~WYQListener()
{
cout << "Destruct WYQListener(" << id << ")" << endl;
}

virtual void notify( void *usrArg )
{
cout << "[" << id << "] is notified as " << (char*)usrArg << endl;
}
};

int main( void )
{
WYQListenerManager manager;

for ( int j = 0; j < 10; ++ j )
{
bool ok = manager.addListener( new WYQListener( j ) );
assert( ok );
}

for ( int i = 0; i < 10; ++ i )
{
if ( i % 2 == 0 )
manager.notify( "Even" );
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐