实现一个MessageHandle消息路由:
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <string>
using namespace std;
template <class T>
class test
{
public:
int getType(){return T::uri;}
virtual bool decode(int){}
};
class test_1 : public test<test_1>
{
public:
enum {uri = 1};
bool decode(int){cout << "test_1 decode" << endl; return true;}
};
class test_2 : public test<test_2>
{
public:
enum {uri = 2};
bool decode(int){cout << "test_2 decode" << endl; return true;}
};
void function1()
{
test_1 t;
cout << "test_1 type " << t.getType() << endl;
test_2 t2;
cout << "test_2 type " << t2.getType() << endl;
}
template<class P>
class callbackP
{
public:
virtual void onPacket(int reader, P& conn) const = 0;
};
template <class T, class P>
class callbackTP : public callbackP<P>
{
public:
typedef function<void(T&, P&)> RoomCb;
callbackTP(const RoomCb& cb):_cb(cb){}
void onPacket(int reader, P& conn) const
{
T t;
if(t.decode(reader)){_cb(t, conn);}
}
private:
RoomCb _cb;
};
template<class P>
class dispatcherP
{
public:
typedef shared_ptr<callbackP<P>> CallBackP;
template<class T>
void register_handle(const typename callbackTP<T, P>::RoomCb& cb)
{
CallBackP ptr(new callbackTP<T, P>(cb));
cm.insert(make_pair(T::uri, ptr));
}
void onPacket(int uri, P conn)
{
auto f = cm.find(uri);
if (f != cm.end())
{
f->second->onPacket(uri, conn);
}
else
{
cout << "not found " << uri << " msg: " << conn << endl;
}
}
private:
typedef map<int, CallBackP> CallBackMap;
CallBackMap cm;
};
class instance
{
public:
void ontest1(const test_1&, int conn)
{
cout << "ontest1 handle callback conn "<<conn<<endl;
}
void ontest2(const test_2&, int conn)
{
cout << "ontest2 handle callback conn "<<conn<<endl;
}
void ontest3(const test_1&, string conn)
{
cout << "ontest3 handle callback conn "<<conn<<endl;
}
void ontest4(const test_2&, string conn)
{
cout << "ontest4 handle callback conn "<<conn<<endl;
}
};
int main(int argc, char const *argv[])
{
instance in;
dispatcherP<int> p1;
p1.register_handle<test_1>(bind(&instance::ontest1, &in, placeholders::_1, placeholders::_2));
p1.register_handle<test_2>(bind(&instance::ontest2, &in, placeholders::_1, placeholders::_2));
p1.onPacket(test_1::uri, 123);
p1.onPacket(test_1::uri, 456);
p1.onPacket(test_2::uri, 123);
dispatcherP<string> p2;
p2.register_handle<test_1>(bind(&instance::ontest3, &in, placeholders::_1, placeholders::_2));
p2.register_handle<test_2>(bind(&instance::ontest4, &in, placeholders::_1, placeholders::_2));
p2.onPacket(test_1::uri, "hello test1");
p2.onPacket(test_1::uri, "hello1 test1");
p2.onPacket(test_2::uri, "hello test2");
return 0;
}