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

组合优于继承

时间:2016-01-30 02:17:37      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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


为什么组合优于继承?

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

两者差别

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 !


组合优于继承

标签:

原文地址:http://www.cnblogs.com/lcchuguo/p/5170139.html

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