如何使用Scala的蛋糕模式来实现机器人腿?
发布时间:2020-12-16 08:55:30 所属栏目:安全 来源:网络整理
导读:我的开发广泛使用机器人腿绑定问题.我知道Guice中的私有模块是 how to solve it,但目前尚不清楚如何使用Scala的蛋糕模式. 有人可以解释一下如何做到这一点,理想情况下,根据Jonas Boner在他blog post年底的咖啡示例得出一个具体的例子吗?也许有一个可以配置
我的开发广泛使用机器人腿绑定问题.我知道Guice中的私有模块是
how to solve it,但目前尚不清楚如何使用Scala的蛋糕模式.
有人可以解释一下如何做到这一点,理想情况下,根据Jonas Boner在他blog post年底的咖啡示例得出一个具体的例子吗?也许有一个可以配置为左侧和右侧的温暖,注入方向和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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |