Skip to content

Instantly share code, notes, and snippets.

@weihsiu
Forked from HarryHuang/cake_pattern_di.scala
Created November 19, 2011 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weihsiu/1379113 to your computer and use it in GitHub Desktop.
Save weihsiu/1379113 to your computer and use it in GitHub Desktop.
Scala Dependency Injection: an improved cake pattern
//harry huang [huanghui.huang@gmail.com]
//
//After reading the original post [http://jboner.github.com/2008/10/06/real-world-scala-dependency-injection-di.html, ]
//the original cake pattern seems quite verbose for me, and it is quite invasive, so I spent a bit time
//and come up with an improved version of cake pattern, which I call it a "Auto Cake DI". It is working
//well with any POST(plain old scala trait)/POSO(plain old scala object) which means that anything can be
//injected without modification or introducing new traits.
/*---------inject trait---------*/
trait Inject[+T] { def inject: T }
object Cake {
// =======================
def main(s: Array[String]) {
val warmer = ComponentRegistry.warmer
warmer.trigger
}
}
// =======================
// service interfaces
trait OnOffDevice {
def on: Unit
def off: Unit
}
trait SensorDevice {
def isCoffeePresent: Boolean
}
class Heater extends OnOffDevice {
def on = println("heater.on")
def off = println("heater.off")
}
class PotSensor extends SensorDevice {
def isCoffeePresent = true
}
// =======================
// service declaring two dependencies that it wants injected
trait WarmerComponentImpl {
this: Inject[(OnOffDevice, SensorDevice)] =>
class Warmer {
def trigger = {
val (onOff, sensor) = inject
if (sensor.isCoffeePresent) onOff.on
else onOff.off
}
}
}
// =======================
// instantiate the services in a module
object ComponentRegistry extends WarmerComponentImpl with Inject[(OnOffDevice, SensorDevice)] {
val inject = (new Heater, new PotSensor)
val warmer = new Warmer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment