加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:03:19 所属栏目:安全 来源:网络整理
导读:在 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. Onl
在 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如何不改变父类的任何内容,但仍然可以在子类型中轻松重用?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读