如何使用 Scala 的蛋糕图案来实现机器人腿?



我的开发广泛使用了机器人腿部绑定问题。我知道如何使用Guice中的PrivateModule来解决这个问题,但还不清楚如何使用Scala的蛋糕模式来实现。

有人能解释一下该如何做到这一点吗?最好是在博客文章末尾以乔纳斯·博纳的咖啡为例,举一个具体的例子?也许可以为左右两侧配置一个加热器,注入一个方向和def isRightSide

Cake模式在最初的形式中并不能解决这个问题。您可以选择如何处理这个问题。我更喜欢的解决方案是通过用适当的参数调用其构造函数来创建每个"机器人腿"——代码比单词更能说明这一点。

我认为上面引用的答案更具可读性,但如果你已经熟悉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

相关内容

  • 没有找到相关文章

最新更新