老调重弹 Composition versus Inheritance

http://www.artima.com/designtechniques/compoinh.html

 

By contrast, a change to a superclass's interface can not only ripple down the inheritance hierarchy to subclasses, but can also ripple out to code that uses just the subclass's interface.

Composition allows you to delay the creation of back-end objects until (and unless) they are needed, as well as changing the back-end objects dynamically throughout the lifetime of the front-end object. With inheritance, you get the image of the superclass in your subclass object image as soon as the subclass is created, and it remains part of the subclass object throughout the lifetime of the subclass.

 

<Code Complete>

 

P145

 

inherited routines come in three basic flavors:

An abstract over-ridable routine meas that the derived class inherits the routine's interface but not its implmentation.

An over-ridable routine means that the derived class inherits the routine's interface and a default implementation and it's allowed to override the default implementation.

An non-overridable routine means that the derived class inherits the routine's interface and its default implementation and it's not allowed to override the routine's implmentation.

 

P149

If multiple classes share common data but not behavior,  create a common object that those classes can contain.

If multiply classes share common behavior but not data, derive them from a common base class that defines he common routines.

If multiply classes share common data and behavior, inherit from a common base class that defines the common data and routines.

Inherit when you want the base class to control your interface; contain when you want to control your interface.

 

区别:

 

逻辑关系:

inheritance 是 is-a relation,

composition 是 has-a relation

 

生命周期:

我们常常说composition和Aggregation的区别在于声明周期, inherit 和 composition似乎也有生命周期上的差别:composition allows you to delay the creation of back-end objects,而inheritance 子类实例创建时,父类的image也相应构造。

 

功能和接口:

如果是想由base class来控制接口,则继承;如果是自己控制接口,想使用base class的功能,则contains

 

继承的几种:

只继承接口,只继承实现/数据,或者both

 

 

什么情况下两者同时使用?

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FireCoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值