Scala学习笔记13【trait之多重继承、AOP实战】

Scala多重继承

Scala多重继承实战代码示例:

class Human{
  println("Human")
}

//定义teacher特性
trait TTeacher extends Human{
  println("TTeacher")
  def teach
}

//定义piano player特性
trait PianoPlayer extends Human{
  println("PianoPlayer")
    def playPiano = {println("I'm playing pinao!")}
}

//同时具有teacher和piano player特性
class PinaoTeacher extends Human with TTeacher with PianoPlayer{
  override def teach = {println("I am a piano teacher.")}
}


object TraitUse {
  def main(args: Array[String]){

    //new PinaoTeacher案例
    println("new PinaoTeacher 案例:")
    val t1 = new PinaoTeacher
    t1.playPiano //继承了PianoPlayer的特性
    t1.teach     //覆盖了TTeacher中的teach

    //new Human 案例
    println
    println("new Human 案例:")
    val t2 = new Human with TTeacher with PianoPlayer{
      override def teach = {println("必须重写teach中未实现的teach!")}
    }
    t2.teach
    t2.playPiano
  }
}

运行结果:

new PinaoTeacher 案例:
Human
TTeacher
PianoPlayer
I'm playing pinao!
I am a piano teacher.

new Human 案例:
Human
TTeacher
PianoPlayer
必须重写TTeacher中未实现的teach!
I'm playing pinao!

AOP(面向切面编程)

可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。

AOP常用基本整体框架代码示例:

trait Action{
  def doAction
}

trait TBeforeAfter extends Action{
  abstract override def doAction{  //因调用super.doAction,仍是抽象方法
    println("初始化")
    super.doAction
    println("销毁")
  }
}

class Work extends Action{
  override def doAction = println("do sth.")
}

object ScalaAOP {
  def main(args: Array[String]){

    //构建从左至右
    val work = new Work with TBeforeAfter
    work.doAction
  }
}

打印输出:

初始化
do sth.
销毁

你可能感兴趣的:(AOP,scala,多重继承)