-
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
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28912557/viewspace-1845125/
,如需转载,请注明出处,否则将追究法律责任。