如果你有 Traits,你会停止使用接口、抽象基类和多重继承吗?
看起来 Traits 可以完全取代接口、抽象基类、mixin 和多重继承,只留下 Traits 和具体继承。
这是意图吗?
如果您有特征,您应该使用哪些其他代码结构?
(角色是 Traits 的 Perl 名称。)
It seems like Traits could completely replace interfaces, abstract base classes, mixins, and multiple inheritance, leaving you with just Traits and concrete inheritance.
Is this the intent?
If you have traits, which of the other code structuring constructs should you use?
(Roles are the Perl name for Traits.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
至少对于 Perl 的 Moose 来说,没有接口,因此角色明确地包含了这些接口,并且通常也包含了 mixin。我想说抽象基类仍然有可能存在。角色可以被认为是对象做什么,而类就是它们是什么。
通过这种推理,抽象基类仍然可能有效。 URL 就是一个例子。 URL 很容易有一个抽象基类。 IO 流可能有所不同,也许作为一个角色更好,因为它定义了事物的行为方式而不是它们是什么。
然而,当使用角色时,我还没有看到任何对来自多个类的真正多重继承的明确需求。
At least for Perl's Moose, there are no interfaces, so roles clearly subsume those, and generally mixins too. I'd say there still could be a case for abstract base classes. Roles can be considered what objects do, where classes are what they are.
By this line of reasoning, there still might be a valid use for an abstract base class. A URL is one example. There could easily be an abstract base class for a URL. An IO stream might be different, perhaps better as a role, as it defines how things behave rather than what they are.
When using roles, however, I have yet to see any clear need for true multiple inheritance from more than one class.
目前我还没有使用接口或抽象类,但是混合和多重继承实际上是由特征启用的,因此这里强烈鼓励使用这些范例。检查整个集合库,看看您可以使用这些想法构建非常丰富的类。
啊,我的评论反映了 Scala - 我没有意识到你用多种语言标记了它。
I have no use for interfaces or abstract classes at this point, but mixins and multiple inheritance are really enabled by traits so the usage of those paradigms is strongly encouraged here. Check the entire collection library to see the very rich classes you can build using these ideas.
Ah, my comments reflect Scala - I didn't realize you tagged this with multiple languages.
当你实例化一个特质时;它消耗一个类。
所以不管表现力如何;您仍然可以使用旧版构造来防止 jar 中的类爆炸(以及启动时间)。
我让其他人回答关于表达力的问题:)
When you instanciate a trait; it consumes one classe.
So regardless of expressivity; You may still use legacy construct for preventing classes explosion in your jar (and starting time).
I let others answer about expressivity :)
我在这里只讨论 Scala...
阅读此。
I'm only talking about Scala here...
Read this.