scala学习笔记-面向对象编程之Trait

将trait作为接口使用

复制代码
 1 // Scala中的Triat是一种特殊的概念
 2 // 首先我们可以将Trait作为接口来使用,此时的Triat就与Java中的接口非常类似
 3 // 在triat中可以定义抽象方法,就与抽象类中的抽象方法一样,只要不给出方法的具体实现即可
 4 // 类可以使用extends关键字继承trait,注意,这里不是implement,而是extends,在scala中没有implement的概念,无论继承类还是trait,统一都是extends
 5 // 类继承trait后,必须实现其中的抽象方法,实现时不需要使用override关键字
 6 // scala不支持对类进行多继承,但是支持多重继承trait,使用with关键字即可
 7 
 8 trait HelloTrait {
 9   def sayHello(name: String)
10 }
11 trait MakeFriendsTrait {
12   def makeFriends(p: Person)
13 }
14 class Person(val name: String) extends HelloTrait with MakeFriendsTrait with Cloneable with Serializable {
15   def sayHello(name: String) = println("Hello, " + name)
16   def makeFriends(p: Person) = println("Hello, my name is " + name + ", your name is " + p.name)
17 }
复制代码

在Trait中定义具体方法

复制代码
 1 // Scala中的Triat可以不是只定义抽象方法,还可以定义具体方法,此时trait更像是包含了通用工具方法的东西// 有一个专有的名词来形容这种情况,就是说trait的功能混入了类
 2 // 举例来说,trait中可以包含一些很多类都通用的功能方法,比如打印日志等等,spark中就使用了trait来定义了通用的日志打印方法
 3 
 4 trait Logger {
 5   def log(message: String) = println(message)
 6 }
 7 
 8 class Person(val name: String) extends Logger {
 9   def makeFriends(p: Person) {
10     println("Hi, I'm " + name + ", I'm glad to make friends with you, " + p.name)
11     log("makeFriends methdo is invoked with parameter Person[name=" + p.name + "]")
12   }
13 }
复制代码

在Trait中定义具体字段

复制代码
 1 // Scala中的Triat可以定义具体field,此时继承trait的类就自动获得了trait中定义的field
 2 // 但是这种获取field的方式与继承class是不同的:如果是继承class获取的field,实际是定义在父类中的;而继承trait获取的field,就直接被添加到了类中
 3 
 4 trait Person {
 5   val eyeNum: Int = 2
 6 }
 7 
 8 class Student(val name: String) extends Person {
 9   def sayHello = println("Hi, I'm " + name + ", I have " + eyeNum + " eyes.")
10 }
复制代码

在Trait中定义抽象字段

复制代码
// Scala中的Triat可以定义抽象field,而trait中的具体方法则可以基于抽象field来编写
// 但是继承trait的类,则必须覆盖抽象field,提供具体的值

trait SayHello {
  val msg: String
  def sayHello(name: String) = println(msg + ", " + name)
}

class Person(val name: String) extends SayHello {
  val msg: String = "hello"
  def makeFriends(p: Person) {
    sayHello(p.name)
    println("I'm " + name + ", I want to make friends with you!")
  }
}
复制代码

为实例混入trait

复制代码
 1 // 有时我们可以在创建类的对象时,指定该对象混入某个trait,这样,就只有这个对象混入该trait的方法,而类的其他对象则没有
 2 
 3 trait Logged {
 4   def log(msg: String) {}
 5 }
 6 trait MyLogger extends Logged {
 7   override def log(msg: String) { println("log: " + msg) }
 8 }  
 9 class Person(val name: String) extends Logged {
10     def sayHello { println("Hi, I'm " + name); log("sayHello is invoked!") }
11 }
12 
13 val p1 = new Person("leo")
14 p1.sayHello
15 val p2 = new Person("jack") with MyLogger
16 p2.sayHello
复制代码

trait调用链

复制代码
 1 // Scala中支持让类继承多个trait后,依次调用多个trait中的同一个方法,只要让多个trait的同一个方法中,在最后都执行super.方法即可
 2 // 类中调用多个trait中都有的这个方法时,首先会从最右边的trait的方法开始执行,然后依次往左执行,形成一个调用链条
 3 // 这种特性非常强大,其实就相当于设计模式中的责任链模式的一种具体实现依赖
 4 trait Handler {
 5   def handle(data: String) {}
 6 }
 7 trait DataValidHandler extends Handler {
 8   override def handle(data: String) {
 9     println("check data: " + data)
10     super.handle(data)
11   } 
12 }
13 trait SignatureValidHandler extends Handler {
14   override def handle(data: String) {
15     println("check signature: " + data)
16     super.handle(data)
17   }
18 }
19 class Person(val name: String) extends SignatureValidHandler with DataValidHandler {
20   def sayHello = { println("Hello, " + name); handle(name) }
21 }
22 
复制代码

在trait中覆盖抽象方法

复制代码
 1 // 在trait中,是可以覆盖父trait的抽象方法的
 2 // 但是覆盖时,如果使用了super.方法的代码,则无法通过编译。因为super.方法就会去掉用父trait的抽象方法,此时子trait的该方法还是会被认为是抽象的
 3 // 此时如果要通过编译,就得给子trait的方法加上abstract override修饰
 4 
 5 trait Logger {
 6   def log(msg: String)
 7 }
 8 
 9 trait MyLogger extends Logger {
10   abstract override def log(msg: String) { super.log(msg) }
11 }
12 
13 
14 
复制代码

混合使用trait的具体方法和抽象方法

复制代码
 1 // 在trait中,可以混合使用具体方法和抽象方法
 2 // 可以让具体方法依赖于抽象方法,而抽象方法则放到继承trait的类中去实现
 3 // 这种trait其实就是设计模式中的模板设计模式的体现
 4 
 5 trait Valid {
 6   def getName: String
 7   def valid: Boolean = {
 8     getName == "leo"    
 9   }
10 }
11 class Person(val name: String) extends Valid {
12   println(valid)
13   def getName = name
14 }
15 
16 
17 
18 
复制代码

trait的构造机制

复制代码
 1 // 在Scala中,trait也是有构造代码的,也就是trait中的,不包含在任何方法中的代码
 2 // 而继承了trait的类的构造机制如下:1、父类的构造函数执行;2、trait的构造代码执行,多个trait从左到右依次执行;3、构造trait时会先构造父trait,如果多个trait继承同一个父trait,则父trait只会构造一次;4、所有trait构造完毕之后,子类的构造函数执行
 3 
 4 class Person { println("Person's constructor!") }
 5 trait Logger { println("Logger's constructor!") }
 6 trait MyLogger extends Logger { println("MyLogger's constructor!") }
 7 trait TimeLogger extends Logger { println("TimeLogger's constructor!") }
 8 class Student extends Person with MyLogger with TimeLogger {
 9   println("Student's constructor!")
10 }
11 
12 
13 
14 
15 
16 
复制代码

trait field的初始化

复制代码
 1 // 在Scala中,trait是没有接收参数的构造函数的,这是trait与class的唯一区别,但是如果需求就是要trait能够对field进行初始化,该怎么办呢?只能使用Scala中非常特殊的一种高级特性——提前定义
 2 trait SayHello {
 3   val msg: String
 4   println(msg.toString)
 5 }
 6 
 7 class Person
 8 val p = new {
 9   val msg: String = "init"
10 } with Person with SayHello
11 
12 class Person extends {
13   val msg: String = "init"
14 } with SayHello {}
15 
16 // 另外一种方式就是使用lazy value
17 trait SayHello {
18   lazy val msg: String = null
19   println(msg.toString)
20 }
21 class Person extends SayHello {
22   override lazy val msg: String = "init"
23 }
24 
25 
26 
27 
复制代码

trait继承class

复制代码
 1 // 在Scala中,trait也可以继承自class,此时这个class就会成为所有继承该trait的类的父类
 2 
 3 class MyUtil {
 4   def printMessage(msg: String) = println(msg)
 5 }
 6 
 7 trait Logger extends MyUtil {
 8   def log(msg: String) = printMessage("log: " + msg)
 9 }
10 
11 class Person(val name: String) extends Logger {
12   def sayHello {
13     log("Hi, I'm " + name)
14     printMessage("Hi, I'm " + name)
15   }
16 }

猜你喜欢

转载自www.cnblogs.com/cxhfuujust/p/9908949.html
今日推荐