Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8058518
  • 博文数量: 594
  • 博客积分: 13065
  • 博客等级: 上将
  • 技术积分: 10324
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-26 16:44
个人简介

推荐: blog.csdn.net/aquester https://github.com/eyjian https://www.cnblogs.com/aquester http://blog.chinaunix.net/uid/20682147.html

文章分类

全部博文(594)

分类: C/C++

2012-06-04 13:11:24

注:原发表在

在进行OO时,很容易做到结构统一,这个也容易理解,如下:
  1. class Parent
  2. {
  3. public:
  4.     virtual void hello() = 0;
  5. };

  6. class Child1: public Parent
  7. {
  8. private:
  9.     virtual void hello() {
  10.         printf("Child1\n"); // 当运行到这里时,调用栈显得和Parent毫无关系
  11.     }
  12. };

  13. class Child2: public Parent
  14. {
  15. private:
  16.     virtual void hello() {
  17.         printf("Child2\n"); // 当运行到这里时,调用栈显得和Parent毫无关系
  18.     }
  19. };

  20. int main() {
  21.     Parent* p = new Child2;
  22.     p->hello();
  23.     return 0;
  24. }
复制代码
在上面的设计中,结构是统一的,对外展现的是Parent,但是行为并非统一,当使用gdb打印调用栈时,是看不到Parent的影子的,当系统庞大后,对新人来理解系统会增加一些阻力。如何解决这个问题了?通过统一行为,就可以将这个清晰化。方法是:在Parent中增加一个非抽象方法,由这个新增加的非抽象方法来调用hello,这样在调用栈中就可以见到Parent的身影了,调用栈显示有层次感,有助于理解系统。
  1. class Parent
  2. {
  3. public:
  4.     /* virtual */ void hello() {
  5.         do_hello();
  6.     }
  7.     
  8. private:
  9.     virtual void do_hello() = 0;
  10. };

  11. class Child1: public Parent
  12. {
  13. private:
  14.     virtual void do_hello() {
  15.         printf("Child1\n"); // 当运行到这里时,调用栈中会包含Parent -> Child1信息
  16.     }
  17. };

  18. class Child2: public Parent
  19. {
  20. private:
  21.     virtual void do_hello() {
  22.         printf("Child2\n"); // 当运行到这里时,调用栈中会包含Parent -> Child2信息
  23.     }
  24. };

  25. int main() {
  26.     Parent* p = new Child2;
  27.     p->hello();
  28.     return 0;
  29. }
复制代码
上面的修改,简单来看,除了增加代码和调用次数的缺点外,没有带来任何好处,但软件开发实则为一项工程性的工作,需要考虑到整体性和外部因素等,个人觉得这样做很值得,特别是当你使用UML作设计时,时序图将显得更有条理性。
阅读(1110) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~