Created
November 10, 2018 01:28
-
-
Save shkesar/8e1ea337ee772a3dd39fae22fc57a159 to your computer and use it in GitHub Desktop.
Dependency Injection
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
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