C++ 单例模式封装问题
今天在学习reactor模型的时候,参考了下别人写的代码。
参考博客地址:https://blog.csdn.net/u011693...
以下为所要提出的问题:
1.既然有reactor类,为何要封装一个reactor_impl类。
2.在单例模式中,reactor类中的构造函数和析构函数被设为私有,按理来说是不能调用的,为何要进行编写。
C++小白,还希望可以学习。
源代码:
reactor.h
#include "event_handler.h"
#include "event.h"
#include "reactor_impl.h"
class ReactorImpl;
class Reactor {
public:
static Reactor& get_instance();
int regist(EventHandler* handler, Event evt);
void remove(EventHandler* handler);
void dispatch(int timeout = 0);
private:
Reactor();
~Reactor();
Reactor(const Reactor&);
Reactor& operator=(const Reactor&);
private:
ReactorImpl* _reactor_impl;
static Reactor reactor;
};
reactor.cpp
#include "reactor.h"
#include <assert.h>
#include <new>
Reactor Reactor::reactor;
Reactor& Reactor::get_instance() {
return reactor;
}
Reactor::Reactor() {
_reactor_impl = new (std::nothrow)ReactorImpl();
assert(_reactor_impl != NULL);
}
Reactor::~Reactor() {
if (_reactor_impl != NULL) {
delete _reactor_impl;
_reactor_impl = NULL;
}
}
int Reactor::regist(EventHandler* handler, Event evt) {
return _reactor_impl->regist(handler, evt);
}
void Reactor::remove(EventHandler* handler) {
return _reactor_impl->remove(handler);
}
void Reactor::dispatch(int timeout) {
return _reactor_impl->dispatch(timeout);
}
reactor_impl.h
#include <map>
#include "event.h"
#include "event_handler.h"
#include "event_demultiplexer.h"
class ReactorImpl {
public:
ReactorImpl();
~ReactorImpl();
int regist(EventHandler* handler, Event evt);
void remove(EventHandler* handler);
void dispatch(int timeout = 0);
private:
EventDemultiplexer* _demultiplexer;
std::map<Handle, EventHandler*> _handlers;
};
reactor_impl.cpp
#include "reactor_impl.h"
#include <new>
#include <assert.h>
#include "epoll_demultiplexer.h"
ReactorImpl::ReactorImpl() {
_demultiplexer = new (std::nothrow)EpollDemultiplexer();
assert(_demultiplexer != NULL);
}
ReactorImpl::~ReactorImpl() {
std::map<Handle, EventHandler*>::iterator iter = _handlers.begin();
for(; iter != _handlers.end(); ++iter) {
delete iter->second;
}
if (_demultiplexer != NULL) {
delete _demultiplexer;
}
}
int ReactorImpl::regist(EventHandler* handler, Event evt) {
int handle = handler->get_handle();
if (_handlers.find(handle) == _handlers.end()) {
_handlers.insert(std::make_pair(handle, handler));
}
return _demultiplexer->regist(handle, evt);
}
void ReactorImpl::remove(EventHandler* handler) {
int handle = handler->get_handle();
// not check?
_demultiplexer->remove(handle);
std::map<Handle, EventHandler*>::iterator iter = _handlers.find(handle);
delete iter->second;
_handlers.erase(iter);
}
void ReactorImpl::dispatch(int timeout) {
_demultiplexer->wait_event(_handlers, timeout);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论