Squeak/Pharo Trait 和 Newpeak Mixin 有什么区别?
所以 Squeak/Pharo 支持 Traits,Newspeak 有 Mixins。有什么区别? Traits 没有 instVars 但 Mixins 有?
So Squeak/Pharo support Traits and Newspeak has Mixins. What is the difference? Traits have no instVars but Mixins have?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了更好地进行比较并解释为什么特征是首选的,您可以查看 特征论文(pdf)。
本质上,这就是 Lukas Renggli 说:
Traits 成员被组合成一个类,并且不改变其继承层次结构。冲突必须由特征的用户明确解决。
Mixin 被线性化到目标类的继承层次结构中。如果存在冲突的成员,则声明它们的顺序将决定调用哪个成员。这是脆弱,因为它隐式定义了组合的行为,并且类作者必须意识到潜在的冲突以及它们将如何影响生成的类。
由于 mixin 被线性化,因此它们不会遭受臭名昭著的多重继承的“钻石问题”。因此,它们堆叠在一起的脆弱性质是另一个问题,我将其称为“红宝石问题”,以与宝石的比喻保持一致。由于一些奇怪的原因,与 moose< /a>,珍珠不能像红宝石那样描述这个问题。
For a good comparison and for the reasoning of why traits are preferred, you can check the traits paper (pdf).
In essence, it's what Lukas Renggli said:
Traits members are composed into a class, and don't change its inheritance hierarchy. Conflicts have to be explicitly resolved by the user of the traits.
Mixins are linearized into the target class' inheritance hierarchy. If there're conflicting members, the order in which they were declared dictates which member gets called. This is fragile because it implicitly defines the behavior of the composition, and the class author must be aware of potential conflicts and how they'll impact the resulting class.
Since mixins get linearized, they don't suffer from the notorious "diamond problem" of multiple-inheritance. So the fragile nature in which they are stacked is another problem, which I'll dub the "ruby problem", to keep with the precious stone metaphor. For some odd reasons that have to do with moose, pearls don't depict the problem as well as rubies.
特征是使用组合规则组合的。冲突必须手动解决,特征不可能意外覆盖另一个同名的方法。
Mixin 是按顺序组成的,因此存在类似于多重继承的脆弱性问题。
Traits are composed using a composition rule. Conflicts have to be resolved manually, it cannot happen that a trait accidentally overrides another method with the same name.
Mixins are composed by order and thus have fragility problems similar to multiple inheritance.
在新话中,所有类都是 mixin。以下是 Gilad Bracha 在 Newspeak 讨论论坛 中对类似问题的回答的一些片段:
In Newspeak all classes are mixins. Here are some snippets from Gilad Bracha's answer to a similar question in Newspeak discussion forum: