用蛋糕取代代表团

时间:2016-09-07 13:35:09

标签: scala

目前,我正在使用委派

的课程上堆叠功能
trait Backend {
  def product(id: Int): String
}

class MyBackend extends Backend {
  def product(id: Int) = "My product"
}

class LoggingBackend(underlying: Backend) extends Backend {
  override def product(id: Int) = {
    println(s"get product $id")
    underlying.product(id)
  }
}

class CachingBackend(underlying: Backend) extends Backend { /* ... */ }

是否可以用这样的代码替换此代码?

trait Logging {
  this : Backend =>

  def product(id: Int) = {
    println(s"get product $id")
    /* Don't know what to write here */
  }
}

class MyLoggingBackend extends MyBackend with Logging

1 个答案:

答案 0 :(得分:3)

您只需要更改Logging

trait Logging extends Backend {
  abstract override def product(id: Int) = {
    println(s"get product $id")
    super.product(id)
  }
}