protbuf协议的自动派发消息?就是不用switch判断的那种, 是如何写的?

求指导一下,如何不使用switch,就可以处理protobuf消息,就好像mvc中的控制器一样。

阅读 2k
1 个回答
#ifndef TEST_USERCONTROLLER_H
#define TEST_USERCONTROLLER_H

#include <iostream>
class UserController {
public:
    void signIn(const char* data) const;
    void signOut(const char* data) const;
};

#endif //TEST_USERCONTROLLER_H
#include "UserController.h"

void UserController::signIn(const char *data) const {
    std::cout << "sign-in" << std::endl;
}

void UserController::signOut(const char *data) const {
    std::cout << "sign-out" << std::endl;
}
#ifndef TEST_PROTONETMANAGER_H
#define TEST_PROTONETMANAGER_H

#include <map>
#include <iostream>
enum METHOD {
    USER_SIGN_IN,
    USER_SIGN_OUT
};
typedef std::function<void(const char*)> callback;
class ProtoNetManager {
public:
    void registerProtoHandler(const int &msgId, const callback &fun);
    void dispatchProto(const int&msgId, const char* data);
private:
    std::map<int, callback> _listenerList;
};

#endif
#include "ProtoNetManager.h"

void ProtoNetManager::registerProtoHandler(const int &msgId, const callback &fun) {
    this->_listenerList[msgId] = fun;
}

void ProtoNetManager::dispatchProto(const int &msgId, const char *data) {
    auto iter = this->_listenerList.find(msgId);
    if (iter != this->_listenerList.end()) {
        this->_listenerList[msgId](data);
    } else {
        std::cout << "warning!!!!!" << std::endl;
    }
}
#include <iostream>
#include "ProtoNetManager.h"
#include "UserController.h"


using namespace std::placeholders;
int main(int argc, const char* argv[]) {

    ProtoNetManager* protoNetManager = new ProtoNetManager();
    UserController*  userController  = new UserController();

    protoNetManager->registerProtoHandler(METHOD::USER_SIGN_IN,
        std::bind(&UserController::signIn, userController, _1)
    );
    protoNetManager->registerProtoHandler(METHOD::USER_SIGN_OUT,
        std::bind(&UserController::signOut, userController, _1)
    );

    protoNetManager->dispatchProto(METHOD::USER_SIGN_IN, "adc");
    protoNetManager->dispatchProto(METHOD::USER_SIGN_OUT, "apc");
    return 0;
}

破解成功!
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题