1

特质 Trait

Trait可堆叠特性

可自由组合你的算法,非常灵活。越靠后的特质越先执行。

特质使用的线性化解读super

abstract class IntQueue {
      def get(): Int

      def put(x: Int)
    }

    class BasicIntQueue extends IntQueue {

      private val buf = new ArrayBuffer[Int]()

      override def get(): Int = buf.remove(0)

      override def put(x: Int): Unit = buf += x
    }

    trait Doubling extends IntQueue {
      abstract override def put(x: Int): Unit = super.put(2 * x)
    }

    trait Increming extends IntQueue {
      abstract override def put(x: Int): Unit = super.put(x + 1)
    }

    trait Filtering extends IntQueue {
      abstract override def put(x: Int): Unit = if (x > 0) super.put(x)
    }


    val myqueue1 = new BasicIntQueue with Doubling with Filtering with Increming
    myqueue1.put(1)
    println(myqueue1.get())

    val myqueue2 = new BasicIntQueue with Increming with Filtering with Doubling
    myqueue2.put(1)
    println(myqueue2.get())

    val myQueue = new BasicIntQueue with Doubling with Increming with Filtering
    myQueue.put(-1)
    println(myQueue.get())

要特质还是不要?

  • 如果某个行为不会被复用
    用具体的类
  • 如果某个行为可能被用于多个互不相关的类
    用特质,只有特质才能被混入类继承关系中位于不同组成部分的类
  • 如果想从Java代码中继承某个行为
    用抽象类
  • 上述问题都考虑之后,仍然没有答案
    试试特质吧

小鸡
214 声望24 粉丝

1.01的365次方=37.8


引用和评论

0 条评论