可自由組合你的算法,很是靈活。越靠後的特質越先執行。算法
特質使用的線性化解讀superide
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())