Skip to content

Instantly share code, notes, and snippets.

@shkesar
Created November 10, 2018 01:28
Show Gist options
  • Save shkesar/8e1ea337ee772a3dd39fae22fc57a159 to your computer and use it in GitHub Desktop.
Save shkesar/8e1ea337ee772a3dd39fae22fc57a159 to your computer and use it in GitHub Desktop.
Dependency Injection
trait Service {
def sendMessage(msg: String, recv: String): Unit
}
class SMSService extends Service {
def sendMessage(msg: String, recv: String) =
println(s"SMS sent to ${recv} containing ${msg}")
}
class EmailService extends Service {
def sendMessage(msg: String, recv: String) =
println(s"Email sent to ${recv} containing ${msg}")
}
trait Consumer {
def processMessage(msg: String, recv: String): Unit
}
class Application(private val service:Service) extends Consumer {
def processMessage(msg: String, recv: String): Unit =
service.sendMessage(msg, recv)
}
trait Injector {
def getConsumer: Consumer
}
class SMSInjector extends Injector {
def getConsumer: Consumer =
new Application(new SMSService)
}
class EmailInjector extends Injector {
def getConsumer: Consumer =
new Application(new EmailService)
}
object Main extends App {
val injector: Injector = new EmailInjector()
val consumer: Consumer = injector getConsumer
consumer.processMessage("Hello", "To you")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment