如何实现有效的 Java 特征?
请告诉我这是否不合适(特别是 Programmers.SE 或其他东西是否更适合这个问题)。
好的。因此,我目前将许多“特征”表达为接口。我们称它们为“可更新”和“可破坏”。将它们表达为接口的缺点是我无法在所有“可破坏”组件之间共享行为;另一方面,将它们表示为抽象类意味着如果没有将混合特征明确定义为另一个抽象类(“UpdateableAndDestructible”),我就无法混合和匹配,而且这感觉像是滥用抽象类功能。然而,如果没有更干净的方法来处理这个问题,这可能就是我最终要做的事情。
对于这个难题的纯 Java 解决方案我有哪些选择?我是否可以描述共享行为,然后根据我认为合适的方式进行混合和匹配,而不必明确描述我将使用的每个排列?
Please let me know if this is inappropriate as formulated (in particular whether Programmers.SE or something would be better for the question.)
Alright. So I've got a number of 'traits' that I'm currently expressing as interfaces. Let's call them "updatable" and "destructible". Expressing them as interfaces has the downside that I can't share behavior between all "destructible" components; on the other hand, expressing these as abstract classes mean I can't mix and match without explicitly defining the mixed trait as another abstract class ("UpdateableAndDestructible") and furthermore this feels like an abuse of the abstract class functionality at that point. It's probably what I'll end up doing if there aren't cleaner ways of handling this, however.
What are my options as far as pure Java solutions to this conundrum? Is it possible for me to describe shared behavior and then mix and match as I see fit without having to explicitly describe every permutation I'll be using?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许您可以通过使用接口和默认实现的组合来实现目标。
喜欢:
仍然很吵,可能没有您想要的那么灵活,但可能比执行 UpdatableAndDestructable 更干净一些。
Maybe you could achieve the goal by using a mix of interfaces and default implementations.
Like:
Still noisy and maybe not as flexible as you would like but maybe a bit cleaner than doing the UpdatableAndDestructable thing.
我认为这个问题没有一个很好的解决方案,但也许有一些可行的解决方案,具体取决于您对样板文件的鄙视程度。
您可以将特征定义为另一个类+接口,它将实例对象作为第一个参数。他们用你想要具有特征的类来实现接口。然后创建调用特征实现上的方法的存根方法。
然后对于特征本身:
正如 Ernest Friedman-Hill 所说,Scala 为你做了这件事(据我所知,这就是它在 JVM 上实现特征的方式)。
I don't think there is a pretty solution to this problem, but maybe a few workable ones depending on how much you despise the boilerplate.
You could define a trait as another class + interface, that takes the instance object as the first parameter. And them implement the interface with the class you want to have the trait. Then create stub methods that call the methods on the trait impl.
And then for the trait itself:
As Ernest Friedman-Hill says tho, Scala does this for you (as I understand it, this is how it implements traits on the JVM).
我知道你说的是“纯 Java”,但这是 Scala 做得很好的事情。 Java 语言本身的局限性是人们采用其他 JVM 语言的强大驱动力......
I know you said "pure Java", but this is something Scala does well. Limitations in the Java language itself are a strong driver for people to adopt other JVM languages...
如果您考虑使用 lombok 作为纯 Java,您可以通过使用
@Delegate
来简化您的生活像这样:In case you consider using lombok as pure Java, you could simplify your life by using
@Delegate
like this: