scala 入門(4)
阿新 • • 發佈:2018-12-23
2015-05-28
周海漢 2015.5.28
賴永浩在介紹python的mixin模式時,曾舉例水果有適合送禮和不適合送禮的。如蘋果和橘子吉利,適合送禮。而梨則表示離別,香蕉表示焦躁,所以不適合送禮。要實現這樣的類當然可以用定義子類繼承的方式,也可以用組合的方式。但這些方式侵入性較強,必須修改實現內部的原始碼。
而mixin模式,翻譯成中文叫混入模式,是侵入性較弱的。只需在定義的地方加上相應的混入基類,該類就有了相應的能力。混入類必須用trait標記。
class Fruit() {} trait Gift { def gift ={ true } } trait NoGift { def gift ={ false } } class Apple(name:String) extends Fruit with Gift { def nm = name } class Pear(name:String) extends Fruit with NoGift{ def nm = name } object BuyFruit{ def main(arr : Array[String]) { val a = new Apple("apple") println(a.nm + a.gift) val p = new Pear("pear") println(p.nm + p.gift) } }
採用混插方式,讓蘋果和梨具有了可以判斷是否適合送禮的能力。mixin相當於外來的專家給的標籤,直接貼在水果上。
[email protected] % scalac mixin.scala
[email protected] % scala -classpath . BuyFruit appletrue pearfalse
如非註明轉載, 均為原創. 本站遵循知識共享CC協議,轉載請註明來源