Reactor反应堆设计模式是高效的I/O设计中常用的模式之一,它是以同步I/O方式来处理I/O事件的。目前常见的开源网络事件库libevent、libev、libuv、muduo都用到了Reactor反应堆设计模式。在服务器开发中,也有不少人基于Reactor反应堆设计模式来封装自己的网络库。下面是用C++实现Reator模式实现的回射服务器
EventHandler.h
#ifndef EVENT_HANDLER_H_
#define EVENT_HANDLER_H_
typedef int Handler;
class EventHandler
{
public:
EventHandler() {}
virtual ~EventHandler() {}
virtual Handler getHandler() = 0;
virtual void handleRead() = 0;
virtual void handleWirte() = 0;
virtual void handleError() = 0;
};
#endif // !EVENT_HANDLER_H_
Poller.h
#ifndef POLLER_H_H_
#define POLLER_H_H_
#include <map>
#include "EventHandler.h"
class Poller
{
public:
Poller() {}
virtual ~Poller() {}
virtual int waitEvent(std::map<Handler, EventHandler*>& handlers, int timeout = 0) = 0;
virtual int regist(Handler handler) = 0;
virtual int remove(Handler handler) = 0;
private:
};
#endif // !POLLER_H_H_
Dispatcher.h
#ifndef DISPATHER_H_H_
#define DISPATHER_H_H_
#include "EventHandler.h"
#include "Poller.h"
#include <map>
class Dispatcher
{
public:
static Dispatcher* getInstance() { return instance; }
int registHandler(EventHandler* handler);
void removeHander(EventHandler* handler);
void dispatchEvent(int timeout = 0);
private:
//单例模式
Dispatcher();
~Dispatcher();
//只声明不实现,用于禁止拷贝构造和赋值构造
Dispatcher(const Dispatcher&);
Dispatcher& operator=(const Dispatcher&);
private:
Poller* _poller;
std::map<Handler, EventHandler*> _handlers;
private:
static Dispatcher* instance;
};
#endif // !DISPATHER_H_H_
Dispatcher.cpp
#include "Dispatcher.h"
#include "EpollPoller.h"
#include <as