8

我的开发大量使用了机器人腿绑定问题。我知道如何在 Guice 中解决它PrivateModule但不清楚如何使用 Scala 的蛋糕模式来解决这个问题。

有人可以解释一下如何做到这一点,理想情况下,以乔纳斯·博纳(Jonas Boner)博客文章结尾处的咖啡示例为基础的具体示例?也许有一个可以为左侧和右侧配置的加热器,注入一个方向和一个def isRightSide

4

1 回答 1

3

蛋糕模式并没有以其原始形式解决这个问题。你有几个选择如何处理它。我更喜欢的解决方案是通过使用适当的参数调用其构造函数来创建每个“机器人腿”——代码比文字显示得更好。

我认为上面引用的答案更具可读性,但如果您已经熟悉 Jonas 的示例,以下是您如何使用方向配置 Warmer:

// =======================
// service interfaces
trait OnOffDeviceComponent {
  val onOff: OnOffDevice
  trait OnOffDevice {
    def on: Unit
    def off: Unit
  }
}
trait SensorDeviceComponent {
  val sensor: SensorDevice
  trait SensorDevice {
    def isCoffeePresent: Boolean
  }
}

// =======================
// service implementations
trait OnOffDeviceComponentImpl extends OnOffDeviceComponent {
  class Heater extends OnOffDevice {
    def on = println("heater.on")
    def off = println("heater.off")
  }
}
trait SensorDeviceComponentImpl extends SensorDeviceComponent {
  class PotSensor extends SensorDevice {
    def isCoffeePresent = true
  }
}
// =======================
// service declaring two dependencies that it wants injected
trait WarmerComponentImpl {
  this: SensorDeviceComponent with OnOffDeviceComponent =>

  // Note: Warmer's orientation is injected by constructor.
  // In the original Cake some mixed-in val/def would be used
  class Warmer(rightSide: Boolean) {
    def isRightSide = rightSide
    def trigger = {
      if (sensor.isCoffeePresent) onOff.on
      else onOff.off
    }
  }
}

// =======================
// instantiate the services in a module
object ComponentRegistry extends
  OnOffDeviceComponentImpl with
  SensorDeviceComponentImpl with
  WarmerComponentImpl {

  val onOff = new Heater
  val sensor = new PotSensor
  // Note: now we need to parametrize each particular Warmer
  // with its desired orientation
  val leftWarmer = new Warmer(rightSide = false)
  val rightWarmer = new Warmer(rightSide = true)
}

// =======================
val leftWarmer = ComponentRegistry.leftWarmer
leftWarmer.trigger
于 2012-01-27T21:43:01.190 回答