OOP哲学(Scala编程中的组合和继承的摘录)

前端之家收集整理的这篇文章主要介绍了OOP哲学(Scala编程中的组合和继承的摘录)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Scala编程中,第239页,第一段说:

Composition and inheritance are two ways to define a new class in
terms of another existing class. If what you’re after is primarily
code reuse,you should in general prefer composition to inheritance.
Only inheritance suffers from the fragile base class problem,in which
you can inadvertently break subclasses by changing a superclass.

对我来说还不清楚.任何人都可以展示这种情况的一个例子,最好有一些代码吗?

解决方法

fragile base class problem对于支持继承的所有系统都是通用的.这意味着对超类型(您继承的类)的更改可以获得意想不到的结果:更改会使您在基类上打破您的假设.有关解释,请参阅 this related SO question&例子.

相比之下,Scala将父类的后添加输出到外部独立特征,您可以使用Mixin Composition将其添加到子类型.请参阅this example,并将“RichIterator”视为您希望在基础AbsIterator上定义后发生的更改.看看mixin如何不改变父类的任何内容,但仍然可以在子类型中轻松重用?

猜你在找的Scala相关文章