event.h
#include <iostream>
#include <string>
using namespace std;
#define DEF_EVENT_TYPE( etype ) \
class _CEvent##etype##_leveling_ \
{ \
public: \
virtual void Do(_EVENT_##etype##_FUN_ARGS) = 0; \
}; \
class CEvent##etype \
{ \
public: \
CEvent##etype() \
{ _pl = NULL; } \
void etype( _EVENT_##etype##_FUN_ARGS ) \
{ if( NULL != _pl ) _pl->Do(_EVENT_##etype##_ACT_ARGS); } \
void Bind( _CEvent##etype##_leveling_ * pl ) \
{ _pl = pl; } \
private: \
_CEvent##etype##_leveling_ *_pl; \
};
#define REG_EVENT_LEVELING( name, etype, platform, fun) \
class _##platform##_##fun##_ : public _CEvent##etype##_leveling_ \
{ \
public: \
_##platform##_##fun##_( platform &p ) : _p(p) \
{ } \
virtual void Do( _EVENT_##etype##_FUN_ARGS ) \
{ _p.fun( _EVENT_##etype##_ACT_ARGS ); } \
public: \
platform &_p; \
}name;
#define _EVENT_Dance_FUN_ARGS void
#define _EVENT_Dance_ACT_ARGS
DEF_EVENT_TYPE( Dance )
#define _EVENT_Rollerskating_FUN_ARGS const string& shoes
#define _EVENT_Rollerskating_ACT_ARGS shoes
DEF_EVENT_TYPE( Rollerskating )
#define _EVENT_Frontier_FUN_ARGS const string& reynolds, const string& pet
#define _EVENT_Frontier_ACT_ARGS reynolds, pet
DEF_EVENT_TYPE( Frontier )
class QQSPeedBoss
{
public:
void dispatchTask()
{
m_dance.Dance();
m_rollerskatinge.Rollerskating("roller shoes");
m_frontier.Frontier("reynold", "penguin");
}
public:
CEventDance m_dance;
CEventRollerskating m_rollerskatinge;
CEventFrontier m_frontier;
};
class YY
{
public:
YY()
: m_dance( *this ), m_rollerskating( *this ), m_frontier( *this )
{
}
void dance()
{
cout << "I'm dancing." << endl;
}
void rollerskating(const string& shoes)
{
cout << "I'm rollerskating by " << shoes << "." << endl;
}
void frontier(const string& reynolds, const string& pet)
{
cout << "I'm driving " << reynolds << " in frontier carring with " << pet << "." << endl;
}
REG_EVENT_LEVELING( m_dance, Dance, YY, dance )
REG_EVENT_LEVELING( m_rollerskating, Rollerskating, YY, rollerskating )
REG_EVENT_LEVELING( m_frontier, Frontier, YY, frontier )
};
main.cpp
#include <iostream>
#include "event.h"
using namespace std;
int main()
{
//4.事件绑定和触发处理(以QQ飞车游戏老板和代练平台为例)
QQSPeedBoss boss;
YY yy;
boss.m_dance.Bind(&yy.m_dance);
boss.m_rollerskatinge.Bind(&yy.m_rollerskating);
boss.m_frontier.Bind(&yy.m_frontier);
boss.dispatchTask();
return 0;
}