【发布时间】:2013-10-09 10:20:01
【问题描述】:
我在设计模式中一次又一次地听到这个favor composition over inheritance。引用的一些原因是
1)Inheritance is strongly coupled where as composition is loosely coupled
2) Inheritance is compile time determined where as composition is run-time
3)Inheritance breaks encapsulation where as composition does not
4) anything else I am not aware of
对于像我这样的初学者来说,通过插图来了解继承和组合在上述几点方面的不同之处,这将是非常棒的。我已经阅读了各种讨论它们的 SO 链接,但是通过这些关键点的示例对 Java 初学者来说非常有用。
我认为清楚地理解差异比仅仅记住要点非常重要。
【问题讨论】:
-
上面编号的几个项目将受益于包含短语“可能”或“可能是”。
-
This nice article 会优雅地回答问题。
标签: java design-patterns inheritance composition