设计模式之Reactor反应堆

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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值