https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance

解答1

Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach. With composition, it's easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type. So the goose is more or less cooked once you derive from TypeA.

My acid test for the above is:

  • Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates Inheritance.

e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane.

  • Does TypeB want only some/part of the behavior exposed by TypeA? Indicates need for Composition.

e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class / both and make it a member of both classes.

Update: Just came back to my answer and it seems now that it is incomplete without a specific mention of Barbara Liskov's Liskov Substitution Principle as a test for 'Should I be inheriting from this type?'

解答2

Think of containment as a has a relationship. A car "has an" engine, a person "has a" name, etc.

Think of inheritance as an is a relationship. A car "is a" vehicle, a person "is a" mammal, etc.

I take no credit for this approach. I took it straight from the Second Edition of Code Complete by Steve McConnell, Section 6.3.

最新文章

  1. Handlebars.js循环中索引(@index)使用技巧(访问父级索引)
  2. 【T_SQL】 基础 事务
  3. javascript保留关键字
  4. Android studio VT-x is disabled
  5. Windows 7下搭建Jmeter测试环境
  6. eclipse启动tomcat错误:A Java Exception has occurred(转)
  7. excel中 lookup的使用
  8. [设计模式] 11 享元模式 Flyweight
  9. Runtime 实现 动态添加属性
  10. 第二十章、启动流程、模块管理与 Loader grub
  11. $resource
  12. poj 1184 广搜进阶题
  13. p类型最大可定义范围
  14. Android 源码编译
  15. python读写protobuf
  16. LeetCode 108. Convert Sorted Array to Binary Search Tree (有序数组转化为二叉搜索树)
  17. codeforces round #419 C. Karen and Game
  18. springboot中使用kindeditor富文本编辑器实现博客功能
  19. idea创建maven SSM项目
  20. confluence6.3.1部署+数据迁移

热门文章

  1. Codeforces Round #427 (Div. 2)—A,B,C,D题
  2. PHP之冒号、endif、endwhile、endfor 是什么鬼?f
  3. pandas_datareader.data 和 fix_yahoo_finance 获取金融数据
  4. #define宏定义
  5. 14.Iterate a Cursor in the mongo Shell-官方文档摘录
  6. Springboot+shiro配置笔记+错误小结
  7. MySQL学习之——锁(转)
  8. Xcode控制台命令
  9. vertical-align和line-height的深入应用
  10. 实现:左边为菜单导航,当一个菜单中包含多个Tabs,并且不同的Tab要根据权限的不同显示。