代码改变世界

Ruby Module与Scala Traits区别

2012-10-05 16:55  h63542  阅读(356)  评论(0)    收藏  举报

这两天翻出Ruby的书看看,看到Ruby中的一些语言特性在其他语言中也有类似实现,决定对照其他几门语言,总结一下差异,加深对语言特性的理解,本篇为对比Ruby  Module与Scala Traits的区别,两个都是Mix-in技术的实现,同为面对对象技术中代码复用的方式,都为了解决多重继承复杂性,实现功能共享,看上去非常像,但是两者有什么区别呢?下面是我的整理:

Scala Traits和Ruby Module分别是Scala和Ruby中可组合的行为单元,a simple composition mechanism for structuring object-oriented programs. essentially a parameterized set of methods; 

对比:

  相同点 不同点
Scala Traits 
  1. 都是Mix-in技术实现
  2. 都能解决多重继承带来的复杂度,又能实现功能共享
  3. 不能单独生成实例

 

  1. 可以继承普通类
  2. 不可以定义实例变量,只能定义方法
  3. 多Traits继承冲突解决依赖Scala Class Linearization[参考1]
Ruby Module
  1. 不能继承普通类,Module直接Include
  2. 可以定义实例变量保持状态
  3. 多Module Include冲突解决策略就近原则[参考2]

 

参考资料:

参考1:《Scala Class Linearization

参考2:《How to pick the method to call when there is mixin method name conflict

Scala Traits例子:

abstract class AbsIterator {
  type T
  def hasNext: Boolean
  def next: T
}
trait RichIterator extends AbsIterator {
  def foreach(f: T => Unit) { while (hasNext) f(next) }
}
class StringIterator(s: String) extends AbsIterator {
  type T = Char
  private var i = 0
  def hasNext = i < s.length()
  def next = { val ch = s charAt i; i += 1; ch }
}
object StringIteratorTest {
  def main(args: Array[String]) {
    class Iter extends StringIterator(args(0)) with RichIterator
    val iter = new Iter
    iter foreach println
  }
}

 

Ruby Module例子:

module Notes
  attr  :concertA
  def tuning(amt)
    @concertA = 440.0 + amt
  end
end

class Trumpet
  include Notes
  def initialize(tune)
    tuning(tune)
    puts "Instance method returns #{concertA}"
    puts "Instance variable is #{@concertA}"
  end
end

# The piano is a little flat, so we'll match it
Trumpet.new(-5.3)