所有人都有義務考慮自己的性格特徵。且必須合理控制這些特徵,而不去質疑他人的性格特徵是否更適合自己。—西塞羅 Trait: 特質 / 特徵 / 特性 / 特色 / 特點 在 Java 裡, 我們使用 介面(Interface)來達到特徵, 用以限定設計規範與多型. 在 Scala 與之相對的則是 Trait, 但比 Interface 還來的強大。 從 JAVA 到 SCALA 的設計論對比在 Java 的中, 繼承規則被限定為"單一繼承", Java 為了解除這個限制而增設了介面(Interface), 來解封其單一繼承的限制魔咒; interface 最大的優點是它能做到對開發者在開發一個新的 API 時, 能對其應有的內容做一個合適"規範", 但很不幸的這 interface 有幾點存在的弊病 ...
Scala 設計構想為此 Scala 提出更佳的解決設計, 使用了關鍵字 trait, 但與 Java 的 interface 並不完全相同 ..., Scala 開發者更喜好用 「組合」而不是繼承,因為組合一個 trait 和多重繼承有著很大的不同。它賦與了 Scala 在混入组合(mix-in composition)中的機制.
trait 特性
Exampletrait Ord { def < (that: Any): Boolean def
<=(that: Any): Boolean = (this < that) || (this == that)
def > (that: Any): Boolean = !(this <= that) def
>=(that: Any): Boolean = !(this < that) } scala> class WisdomFish defined class WisdomFish scala> trait TWater extends WisdomFish { | def fire | } defined trait TWater scala> abstract class WisdomFish02 extends WisdomFish with TWater defined class WisdomFish02 實例化時 mix-in scala> val fish = new Wisdomfish with TWater with TFire Trait => AOPTrait 因其本身帶來的優異性, 故在進行類似 Java AOP 的開發是很棒的替代物. widening thin interfaces to rich ones橫軋寬展精簡型介面到富介面 / 擴寬瘦接口到胖接口 References
|
C06.物件導向設計(OOP) >