首页 > 代码库 > 组合优于继承
组合优于继承
原文地址: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,属于关系。
组合优于继承的理由
- java不支持多重继承,假如你需要多个功能的时候的话,你就不能使用继承,因为只能继承一个类。
- 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.
- 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.
- 组合更灵活,这一点可以参照我前面讲到的Comparator interface,比如我们需要一个继承了Comparator接口的工具类,此时我们应该选择组合方式,而不是继承这个工具类,因为如果你选择继承的话,那么你在运行时只有一种比较的选择,而这种工具类我们可以定义多个,使用组合的话,我们就可以在运行时进行选择哪个工具类。
Reference
- Prefer composition over inheritance?
- Why Favor Composition over Inheritance in Java and Object Oriented Programming
2014-11-18 23:44:27
Brave,Happy,Thanksgiving !
组合优于继承
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。