組合優於繼承

原文地址: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 !


發佈了142 篇原創文章 · 獲贊 104 · 訪問量 87萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章