Created
November 19, 2011 11:54
-
-
Save HarryHuang/1378765 to your computer and use it in GitHub Desktop.
Scala Dependency Injection: an improved cake pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//harry huang [[email protected]] | |
// | |
//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 "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