对象组合与类继承的缺点 [英] Disadvantage of object composition over class inheritance

查看:99
本文介绍了对象组合与类继承的缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数设计图案说我们应该倾向于类继承中的对象组合。



但任何人都可以给我一个例子,说明继承比对象组合更好。 / p>

解决方案

在Java中,每当您从类继承时,您的新类也将自动成为原始类类型的子类型。由于它是一个子类型,因此需要遵守 Liskov替代原则

这个原则基本上说,你必须能够使用超类型所期望的任何地方的子类型。这严重限制了您的新继承类的行为如何与原始类别不同。

没有编译器能够使您遵守这一原则,但是如果您不能,特别是当其他程序员正在使用你的类时。



在允许子类化而不使用子类型的语言中(如 CZ语言),规则对象构成过度继承并不像Java或C#这样的语言那么重要。


Most design patten books say we should "Favor object composition over class inheritance."

But can anyone give me an example that inheritance is better than object composition.

解决方案

In Java, whenever you inherit from a class, your new class also automatically becomes a subtype of the original class type. Since it is a subtype, it needs to adhere to the Liskov substitution principle.
This principle basically says that you must be able to use the subtype anywhere where the supertype is expected. This severely limits how the behavior of your new inherited class can differ from the original class.
No compiler will be able to make you adhere to this principle though, but you can get in trouble if you don't, especially when other programmers are using your classes.

In languages that allow subclassing without subtyping (like the CZ language), the rule "Favor object composition over inheritance" is not as important as in languages like Java or C#.

这篇关于对象组合与类继承的缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆