Java中mixin的一个例子? [英] An example of a mixin in Java?

查看:161
本文介绍了Java中mixin的一个例子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了Effective Java的第93-4页,但我遇到了一个混合术语。但我发现很难想象出mixin究竟是什么。有没有人可以通过提供Java中的Mixin示例来帮助我。谢谢你的帮助,因为我搜索了Stackoverfolw和互联网,但没有发现任何确定的结论。

I have just been reading page 93-4 of Effective Java, but I have come across the term a mixin. But I am finding it difficult to visualise what a mixin actually is. Could anybody please help me out by providing an example of a Mixin in Java. Thank you for your help because I have searched Stackoverfolw and the Internet, but found nothing really conclusive of clear.

推荐答案

你是参考 Effective Java - 首选接口到抽象类,我特别相信以下部分:

You're referring to Item 18 of Effective Java - Prefer interfaces to abstract classes, and I believe the following section in particular:


接口非常适合定义mixins。松散地说, mixin
类的类型除了它的主要类型之外,它还可以声明它提供了一些
的可选行为。例如 Comparable 是一个mixin接口,允许类为
声明它的实例是针对其他可相互比较的对象进行排序的。
这样的界面叫做mixin,因为它允许可选功能混合
in到该类型的主要功能。抽象类不能用于定义
的mixins,原因是它们不能被改装到现有类中:一个类不能有多个b $ b多于一个父类,并且没有合理的位置插入
mixin的类层次结构。

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.

基本上,在抽象类中指定功能和在接口中,接口版本可以在许多不同的类层次结构中使用,而抽象类只能在一个类层次结构树中使用,因为Java只允许单继承。

Essentially, one of the key differences between specifying functionality in an abstract class and in an interface is that the interface version can be used in a number of different class hierarchies, whereas an abstract class can only be used in the one class hierarchy tree because Java only allows single-inheritance.

这篇关于Java中mixin的一个例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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