组合优于继承

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


转载于:https://www.cnblogs.com/lcchuguo/p/5170139.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值