码迷,mamicode.com
首页 > 其他好文 > 详细

组合优于继承

时间:2014-11-19 00:56:51      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   os   使用   

原文地址:http://leihuang.org/2014/11/18/composition-inheritance/


为什么组合优于继承?

这是一个很典型的设计模式的问题,Head First Design Pattern第一章好像就讲了,之前看得有点忘了。下面我把stackoverflow上面得分比较高的答案搬过来用一下,我觉得这样更容易理解些。

两者区别

Think of composition 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.

上面两句话虽然没讲为什么组合更优秀,但是对于两者的区别却一针见血的说出来了。

简单翻译一下,组合适用于,存在关系的类,就是说Class B只需要Class A的某一个功能。

继承则是属于关系,就是B extends A的话,那么B is A,属于关系。

组合优于继承的理由

  1. java不支持多重继承,假如你需要多个功能的时候的话,你就不能使用继承,因为只能继承一个类。
  2. Composition offers better testability of a class than Inheritance. If one class is composed of another class, you can easily create Mock Object representing composed class for sake of testing. Inheritance doesn‘t provide this luxury. In order to test derived class, you must need its super class. Since unit testing is one of the most important thing to consider during software development, especially in test driven development, composition wins over inheritance.
  3. Many object oriented design patterns mentioned by Gang of Four in there timeless classic Design Patterns: Elements of Reusable Object-Oriented Software, favors Composition over Inheritance. Classical examples of this is Strategy design pattern, where composition and delegation is used to change Context’s behavior, without touching context code. Since Context uses composition to hold strategy, instead of getting it via inheritance, it’s easy to provide a new Strategy implementation at runtime. Another good example of using composition over inheritance is Decorator design pattern. In Decorator pattern, we don‘t extend any class to add additional functionality, instead we keep an instance of the class we are decorating and delegates original task to that class after doing decoration. This is one of the biggest proof of choosing composition over inheritance, since these design patterns are well tried and tested in different scenarios and withstand test of time, keeping there head high.
  4. 组合更灵活,这一点可以参照我前面讲到的Comparator interface,比如我们需要一个继承了Comparator接口的工具类,此时我们应该选择组合方式,而不是继承这个工具类,因为如果你选择继承的话,那么你在运行时只有一种比较的选择,而这种工具类我们可以定义多个,使用组合的话,我们就可以在运行时进行选择哪个工具类。

Reference

  1. Prefer composition over inheritance?
  2. Why Favor Composition over Inheritance in Java and Object Oriented Programming

2014-11-18 23:44:27

Brave,Happy,Thanksgiving !


组合优于继承

标签:des   style   blog   http   io   ar   color   os   使用   

原文地址:http://blog.csdn.net/speedme/article/details/41262295

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!