15.Scala多重继承、多重继承构造器执行顺序及AOP实现

来源:互联网 发布:nestopia mac 编辑:程序博客网 时间:2024/05/21 14:52

一、多重继承的trait代码实战

class Human { println("Human") }trait TTeacher extends Human {  println("TTeacher")    def teach}trait PianoPlayer extends Human {  println("PianoPlayer")    def playPiano  = { println("I'm playing piano")}}class PianoTeacher extends Human with TTeacher with PianoPlayer {  override def teach = {println("I'm training students.")}}object AOP_15 extends App{  val t1 = new PianoTeacher t1.playPiano t1.teach}

输出:

Human
TTeacher
PianoPlayer
I'm playing piano
I'm training students.

3.基于trait的AOP代码实战

trait Action{  def doAction}trait TBeforeAfter extends Action{  abstract override def doAction{   //注意这里的修饰符abstract和override,因为下面的super.doAction是抽象的    println("Initialization")    super.doAction    println("Destroyed")  }}class Work extends Action{  override def doAction = {    println("working")  }}object AOP_15 extends App{  val work = new Work with TBeforeAfter  work.doAction} 

输出:

Initialization
working
Destroyed


参考资料来源于 DT大数据梦工厂Scala零基础实战经典第15课 由王家林老师讲解


阅读全文
0 0