Scala多繼承以及AOP

541732025發表於2015-11-24

點選(此處)摺疊或開啟

  1. class Human{
  2.   println("Human")
  3. }

  4. trait TTeacher extends Human {
  5.   println("TTeacher")
  6.   def teach

  7. trait PianoPlayer extends Human {
  8.   println("PianoPlayer")
  9.   def playPiano = {println("I am playing piano. ")}

  10. class PianoTeacher extends Human with TTeacher with PianoPlayer { //構造PianoTeacher例項時,按照從左至右的順序依次完成,僅構造一次
  11.     override def teach = {println("I am training students. ")}
  12. }

  13. object UseTrait extends App{
  14.    val t1 = new PianoTeacher
  15.    t1.playPiano
  16.    t1.teach
  17. }
結果:
Human
TTeacher
PianoPlayer
I am playing piano.
I am training students.

點選(此處)摺疊或開啟

  1. //AOP
  2. trait Action {
  3.     def doAction
  4. }

  5. trait TBeforeAfter extends Action {
  6.     abstract override def doAction {
  7.         println("Initialization")
  8.         super.doAction //因為呼叫了父類的抽象方法,所以本方法也是抽象的。super.doAction最終會在子類Work中實現,有點類似於模板方法設計模式。
  9.         println("Destroyed")
  10.     }
  11. }

  12. class Work extends Action{
  13.      override def doAction = println("Working...")
  14. }

  15. object UseTrait extends App{
  16.     val work = new Work with TBeforeAfter
  17.     work.doAction
  18. }
結果:
Initialization
Working...
Destroyed

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28912557/viewspace-1845125/,如需轉載,請註明出處,否則將追究法律責任。

相關文章