Created
June 13, 2011 17:49
-
-
Save tomasherman/1023297 to your computer and use it in GitHub Desktop.
Scala structural type dependency injection between modules
This file contains 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
// This file is assumed to be in the API module | |
// ======================= | |
// service interfaces | |
trait OnOffDevice { | |
def on: Unit | |
def off: Unit | |
} | |
trait SensorDevice { | |
def isCoffeePresent: Boolean | |
} | |
// ======================= | |
// service implementations | |
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, | |
// is using structural typing to declare its dependencies | |
class Warmer(env: { | |
val potSensor: SensorDevice | |
val heater: OnOffDevice | |
}) { | |
def trigger = { | |
if (env.potSensor.isCoffeePresent) env.heater.on | |
else env.heater.off | |
} | |
} | |
trait Config { | |
lazy val potSensor:SensorDevice | |
lazy val heater:OnOfDevice | |
lazy val warmer:Warmer | |
} | |
//for simplicity there is no error handling | |
object CodecRepository { | |
var config:Config = null | |
} | |
This file contains 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
//This file is assumed to be in the server module | |
class ConfigImpl extends Config { | |
lazy val potSensor = new PotSensor | |
lazy val heater = new Heater | |
lazy val warmer = new Warmer(this) // this is where injection happens | |
} | |
CodecConfig.config = new ConfigImpl | |
// following part can be in plugin as well | |
class Client(env : { val warmer: Warmer }) { | |
env.warmer.trigger | |
} | |
new Client(CodecConfig.config) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment