面向对象编程

最近在学习高并发的网络库,这个库采用的是基于面向对象的编程思想写的。以前都是面向对象,第一次听说基于对象编程,在此记下自己的学习心得。

在库中作者使用boost::function/bind来实现,boost::function/bind在stl中也有类似的容器,都是适配器。下面看例子。

一、面向对象编程方式

(1)定义一个抽象线程类,留一个虚函数接口给派生类


 
 
  1. class Thread
  2. {
  3. public:
  4. Thread();
  5. virtual ~Thread();
  6. void Start();
  7. void Join();
  8. void SetAutoDelete(bool autoDelete);
  9. private:
  10. static void* ThreadRoutine(void* arg);
  11. virtual void Run() = 0;
  12. pthread_t threadId_;
  13. bool autoDelete_;
  14. };
  15. ( 2) class TestThreadclass Thread继承,派生类只需实现run()函数将基类中的覆盖即可

 
 
  1. class TestThread : public Thread
  2. {
  3. public:
  4. TestThread( int count) : count_(count)
  5. {
  6. cout<< "TestThread ..."<< endl;
  7. }
  8. ~TestThread()
  9. {
  10. cout<< "~TestThread ..."<< endl;
  11. }
  12. private:
  13. void Run()
  14. {
  15. while (count_--)
  16. {
  17. cout<< "this is a test ..."<< endl;
  18. sleep( 1);
  19. }
  20. }
  21. int count_;
  22. };
上面个人写的简单的例子,大家都能看的懂,这样做的话基类就必须暴露一个接口出来给派生类,让派送类重写这个接口实现必要的功能。


 
 
  1. int main(void)
  2. {
  3. TestThread t(5);
  4. t.Start();
  5. t.Join();
  6. return 0;
  7. }

下面看基于对象的编程例子。

二、基于对象的编程

(1)定义一个线程类,但不留接口


 
 
  1. class Thread
  2. {
  3. public:
  4. typedef boost::function< void ()> ThreadFunc;
  5. explicit Thread(const ThreadFunc& func);
  6. void Start();
  7. void Join();
  8. void SetAutoDelete(bool autoDelete);
  9. private:
  10. static void* ThreadRoutine(void* arg);
  11. void Run();
  12. ThreadFunc func_;
  13. pthread_t threadId_;
  14. bool autoDelete_;
  15. };
(2)定义一个类,但不从class Thread派生


 
 
  1. class Foo
  2. {
  3. public:
  4. Foo( int count) : count_(count)
  5. {
  6. }
  7. void MemberFun()
  8. {
  9. while (count_--)
  10. {
  11. cout<< "this is a test ..."<< endl;
  12. sleep( 1);
  13. }
  14. }
  15. void MemberFun2(int x)
  16. {
  17. while (count_--)
  18. {
  19. cout<< "x="<<x<< " this is a test2 ..."<< endl;
  20. sleep( 1);
  21. }
  22. }
  23. int count_;
  24. };
这个时候通过boost::bind来将具体功能函数注册到class Thread


 
 
  1. int main(void)
  2. {
  3. Thread t1(ThreadFunc);
  4. t1.Start();
  5. t1.Join();
  6. return 0;
  7. }

通过上面简单的例子可以看到,面向对象和基于面向对象的主要区别在 回调的方式不同;之所以叫基于面向对象,因为使用了类。如果是c的话,具体功能函数就是全局的函数。关于boost::bind/function大家可以查看boost的相关文档来学习。以上只是个人学习中的一些浅见,在此记录。有不妥之处望大家指正。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值