8
我的開發廣泛使用機器人腿綁定問題。在Guice我知道how to solve it與PrivateModule
,但不清楚Scala的蛋糕模式將如何實現。如何使用Scala的蛋糕模式來實現機器人腿?
有人可以解釋一下這是怎麼完成的,理想情況下是基於Jonas Boner在他的blog post末尾的咖啡示例的具體示例?也許用一個可以配置爲左側和右側的加熱器,注入方向和def isRightSide
?
我的開發廣泛使用機器人腿綁定問題。在Guice我知道how to solve it與PrivateModule
,但不清楚Scala的蛋糕模式將如何實現。如何使用Scala的蛋糕模式來實現機器人腿?
有人可以解釋一下這是怎麼完成的,理想情況下是基於Jonas Boner在他的blog post末尾的咖啡示例的具體示例?也許用一個可以配置爲左側和右側的加熱器,注入方向和def isRightSide
?
蛋糕模式不能以其原始形式解決此問題。你有several choices如何處理。我更喜歡的解決方案是通過使用適當的參數調用它的構造函數來創建每個「機器人腿」 - code表示比單詞更好。
我認爲上面提到的答案是更具可讀性,但如果你已經熟悉了喬納斯例子,這裏是你將怎樣做暖配置有定向:
// =======================
// 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