美文网首页
Scala多继承以及AOP

Scala多继承以及AOP

作者: 田真的架构人生 | 来源:发表于2017-08-01 21:21 被阅读0次
    class Human{
      println("Human")
    }
    
    trait TTeacher extends Human { 
      println("TTeacher")
      def teach 
    } 
    
    trait PianoPlayer extends Human { 
      println("PianoPlayer")
      def playPiano = {println("I am playing piano. ")} 
    } 
    
    class PianoTeacher extends Human with TTeacher with PianoPlayer { //构造PianoTeacher实例时,按照从左至右的顺序依次完成,仅构造一次
        override def teach = {println("I am training students. ")} 
    }
    
    object UseTrait extends App{
       val t1 = new PianoTeacher
       t1.playPiano 
       t1.teach 
    }
    

    结果:
    Human
    TTeacher
    PianoPlayer
    I am playing piano.
    I am training students.

    //AOP
    trait Action { 
        def doAction 
    }
    
    trait TBeforeAfter extends Action { 
        abstract override def doAction { 
            println("Initialization") 
            super.doAction //因为调用了父类的抽象方法,所以本方法也是抽象的。super.doAction最终会在子类Work中实现,有点类似于模板方法设计模式。
            println("Destroyed") 
        } 
    }
    
    class Work extends Action{
         override def doAction = println("Working...")
    }
    
    object UseTrait extends App{
        val work = new Work with TBeforeAfter
        work.doAction
    }
    

    结果:
    Initialization
    Working...
    Destroyed

    相关文章

      网友评论

          本文标题:Scala多继承以及AOP

          本文链接:https://www.haomeiwen.com/subject/qqeslxtx.html