scala 特质的应用

一.为类提供可以堆叠的改变

package com.jason.qianfeng

trait Loggertest {
  def logger(msg: String)
}

trait ConsoleLogger extends Loggertest {
  override def logger(msg: String): Unit = println(msg)
}

trait TimestampLogger extends ConsoleLogger {
  override def logger(msg: String): Unit = super.logger(s"${java.time.Instant.now()} : $msg")
}

trait ShortterLogger extends ConsoleLogger {
  override def logger(msg: String): Unit = {
    val msgLenghth = 16
    if (msg.length > msgLenghth) {
      super.logger(msg.take(13) + "...")
    } else {
      super.logger(msg)
    }
  }
}

abstract class Account {
  protected var balance = 0.0
}

class Saving extends Account with ConsoleLogger {
  def withdraw(ammount: Double): Unit = {
    if (ammount > balance) logger(s"balance is not enough")
    else balance -= ammount
  }
}

object TraitTest2 {
  def main(args: Array[String]): Unit = {
    val acc1 = new Saving with TimestampLogger with ShortterLogger
    val acc2 = new Saving with ShortterLogger with TimestampLogger
    val acc3 = new Saving with ShortterLogger
    val acc4 = new Saving with TimestampLogger
    val acc5 = new Saving
    acc1.withdraw(100.0)
    acc2.withdraw(100.0)
    acc3.withdraw(100.0)
    acc4.withdraw(100.0)
    acc5.withdraw(100.0)
  }
}

输出结果

2018-08-25T13:14:53.644Z : balance is no... // 先截断msg 再 加上timestamp
2018-08-25T13... //先给msg加上timestamp 再 截断
balance is no...
2018-08-25T13:14:53.814Z : balance is not enough
balance is not enough

1.创建Saving 实例时所混入的特质必须是ConsoleLogger的子类,否则会报错

2.程序执行时按照从右到左的顺序调用特质的方法

二.特质当做父接口使用

package com.jason.qianfeng

trait Logger3 {
  def log(msg: String)

  def info(msg: String) = log(s"INFO : $msg")

  def warn(msg: String) = log(s"WARN : ${msg}")

  def severe(msg: String) = log(s"SEVERE : $msg")
}

class Accout3 {
  protected var balance = 0.0
}

class Saving3 extends Accout3 with Logger3 {
  override def log(msg: String): Unit = println(msg)

  def withDraw(ammount: Double) = {
    if (ammount > balance) {
      severe("insufficient funds")
    } else {
      balance -= ammount
      info(s"withdraw funds ${ammount}")
    }
  }
}


object TraitTest3 {
  def main(args: Array[String]): Unit = {
    val sav = new Saving3()
    sav.withDraw(100)
  }
}

在Logger3中定义了抽象方法log,Saving3中对log方法进行了实现,并且可以调用Logger3 的 其他方法

 

posted @ 2018-08-25 22:07  生心无住  阅读(186)  评论(0编辑  收藏  举报