Mixins vs.特质 [英] Mixins vs. Traits

查看:91
本文介绍了Mixins vs.特质的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Mixins和Traits有什么区别?

What is the difference between Mixins and Traits?

根据Wikipedia ,Ruby模块有点像特征.怎么这样?

According to Wikipedia, Ruby Modules are sort of like traits. How so?

推荐答案

  1. 杂种可能包含状态,(传统)特征不包含.
  2. 小伙伴使用内隐冲突解决",特质使用显式冲突解决"
  3. Mixins依赖于线性化,特征被展平.

关于特征的讲座

广告1. 在mixins中,您可以定义实例变量.特质不允许这样做.必须通过组成类(使用特质的类)来提供状态

ad 1. In mixins you can define instance variables. Traits do not allow this. The state must be provided by composing class (=class using the traits)

广告2. 可能存在名称冲突.两个混入(MAMB)或特征(TATB)定义具有相同定义foo():void的方法.

ad 2. There may be the name conflict. Two mixins (MA and MB) or traits (TA and TB) define method with the same definition foo():void.

Mixin MA {
    foo():void {
        print 'hello'
    }
}

Mixin MB {
    foo():void {
        print 'bye'
    }
}

Trait TA {
    foo():void {
        print 'hello'
    }
}

Trait TB {
    foo():void {
        print 'bye'
    }
}

在mixins中,隐式解决了组成类C mixins MA, MB中的冲突.

In mixins the conflicts in composing class C mixins MA, MB are resolved implicitly.

Class C mixins MA, MB {
    bar():void {
        foo();
    }
}

这将从MA

另一方面,在使用特质"时,编写类必须解决冲突.

On the other hand while using Traits, composing class has to resolve conflicts.

Class C mixins TA, TB {
    bar():void {
        foo();
    }
}

此代码将引发冲突(foo():void的两个定义).

This code will raise conflict (two definitions of foo():void).

广告3. 方法的语义不取决于它是在特征中定义还是在使用该特征的类中定义.

ad 3. The semantics of a method does not depend of whether it is defined in a trait or in a class that uses the trait.

换句话说,当类由Traits组成或将Traits代码复制-粘贴"到类中时,都没关系.

In other words, it does not matter wheter the class consists of the Traits or the Traits code is "copy - pasted" into the class.

这篇关于Mixins vs.特质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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