最近在学习高并发的网络库,这个库采用的是基于面向对象的编程思想写的。以前都是面向对象,第一次听说基于对象编程,在此记下自己的学习心得。
在库中作者使用boost::function/bind来实现,boost::function/bind在stl中也有类似的容器,都是适配器。下面看例子。
一、面向对象编程方式
(1)定义一个抽象线程类,留一个虚函数接口给派生类
-
class Thread
-
{
-
public:
-
Thread();
-
virtual ~Thread();
-
-
void Start();
-
void Join();
-
-
void SetAutoDelete(bool autoDelete);
-
-
private:
-
static void* ThreadRoutine(void* arg);
-
virtual void Run() =
0;
-
pthread_t threadId_;
-
bool autoDelete_;
-
};
-
(
2)
class TestThread从class Thread继承,派生类只需实现run()函数将基类中的覆盖即可
-
-
class TestThread :
public Thread
-
{
-
public:
-
TestThread(
int count) : count_(count)
-
{
-
cout<<
"TestThread ..."<<
endl;
-
}
-
-
~TestThread()
-
{
-
cout<<
"~TestThread ..."<<
endl;
-
}
-
-
private:
-
void Run()
-
{
-
while (count_--)
-
{
-
cout<<
"this is a test ..."<<
endl;
-
sleep(
1);
-
}
-
}
-
-
int count_;
-
};
上面个人写的简单的例子,大家都能看的懂,这样做的话基类就必须暴露一个接口出来给派生类,让派送类重写这个接口实现必要的功能。
-
int main(void)
-
{
-
-
TestThread t(5);
-
t.Start();
-
-
t.Join();
-
-
return
0;
-
}
下面看基于对象的编程例子。
二、基于对象的编程
(1)定义一个线程类,但不留接口
-
class Thread
-
{
-
public:
-
typedef boost::function<
void ()> ThreadFunc;
-
explicit Thread(const ThreadFunc& func);
-
-
void Start();
-
void Join();
-
-
void SetAutoDelete(bool autoDelete);
-
-
private:
-
static void* ThreadRoutine(void* arg);
-
void Run();
-
ThreadFunc func_;
-
pthread_t threadId_;
-
bool autoDelete_;
-
};
(2)定义一个类,但不从class Thread派生
-
class Foo
-
{
-
public:
-
Foo(
int count) : count_(count)
-
{
-
}
-
-
void MemberFun()
-
{
-
while (count_--)
-
{
-
cout<<
"this is a test ..."<<
endl;
-
sleep(
1);
-
}
-
}
-
-
void MemberFun2(int x)
-
{
-
while (count_--)
-
{
-
cout<<
"x="<<x<<
" this is a test2 ..."<<
endl;
-
sleep(
1);
-
}
-
}
-
-
int count_;
-
};
这个时候通过boost::bind来将具体功能函数注册到class Thread
-
int main(void)
-
{
-
Thread t1(ThreadFunc);
-
t1.Start();
-
t1.Join();
-
-
return
0;
-
}
通过上面简单的例子可以看到,面向对象和基于面向对象的主要区别在 回调的方式不同;之所以叫基于面向对象,因为使用了类。如果是c的话,具体功能函数就是全局的函数。关于boost::bind/function大家可以查看boost的相关文档来学习。以上只是个人学习中的一些浅见,在此记录。有不妥之处望大家指正。