gpt4 book ai didi

scala - 如何使用 Scala 的蛋糕模式来实现机器人腿?

转载 作者:行者123 更新时间:2023-12-04 08:45:41 25 4
gpt4 key购买 nike

我的开发大量使用了机器人腿绑定(bind)问题。我知道how to solve itPrivateModule在 Guice 中,但尚不清楚如何使用 Scala 的蛋糕模式来完成。

有人可以解释一下如何做到这一点,理想情况下,在他的 blog post 末尾有一个基于 Jonas Boner 的咖啡示例的具体示例?也许有一个可以为左右两侧配置的加热器,注入(inject)一个方向和一个def isRightSide ?

最佳答案

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

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

关于scala - 如何使用 Scala 的蛋糕模式来实现机器人腿?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9035159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com