java - Java 中 mixin 的示例?

标签 java mixins

在《Effective Java》第 93-4 页上,我遇到了术语“mixin”。但我发现很难想象 mixin 到底是什么。有人可以通过提供 Java 中 mixin 的示例来帮助我吗?

最佳答案

您指的是 Effective Java 的第 18 项- 更喜欢接口(interface)而不是抽象类,我特别相信以下部分:

Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a type that a class can implement in addition to its "primary type" to declare that it provides some optional behaviour. For exampleComparable is a mixin interface that allows a class to declare that it its instances are ordered with respect to other mutually comparable objects. Such an interface is called mixin because it allows the optional functionality to be "mixed in" to the type's primary functionality. Abstract classes can't be used to define mixins for the same reason that they can't be be retrofitted onto existing classes: a class cannot have more than one parent, and there is no reasonable place in the class hierarchy to insert a mixin.

本质上,在抽象类和接口(interface)中指定功能之间的主要区别之一是接口(interface)版本可以在许多不同的类层次结构中使用,而抽象类只能在一个类层次结构中使用树,因为Java只允许单继承。

关于java - Java 中 mixin 的示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17987704/

相关文章:

python - 让 PyC​​harm 知道哪些类是 mixin 的

java - PropertySourcesPlaceHolderConfigurer 与 PropertyOverrideConfigurer 等效

java - Maven 不清理子项目目标文件夹

html - 如何使用 px 回退使 Compass Vertical Rhythm 输出 Rems 而不是 Ems?

ruby - ruby mixin 中奇怪的继承

python - 尝试覆盖 django rest 框架中的更新方法以在更新后返回整个查询集

java - 具有多种有界类型的逗号或&符号?

Java printf指定可变宽度

Java 正则表达式 html 解析器

python - 使用mixins来实现抽象方法可以吗?