Skip to content

Instantly share code, notes, and snippets.

@5AbhishekSaxena
Created April 25, 2021 12:11
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 5AbhishekSaxena/203795caf46f7a321623d05d5915f3b1 to your computer and use it in GitHub Desktop.
Save 5AbhishekSaxena/203795caf46f7a321623d05d5915f3b1 to your computer and use it in GitHub Desktop.
Design pattern used to implement IoC. It allows creating the dependent objects outside of the class and provides those objects in different ways.
fun main() {
val redSauce = RedSauce()
val whiteSauce = WhiteSauce()
val greenSauce = GreenSauce()
val redSaucePasta = Pasta(redSauce)
println(redSaucePasta.getPasta())
val whiteSaucePasta = Pasta(whiteSauce)
println(whiteSaucePasta.getPasta())
val greenSaucePasta = Pasta(greenSauce)
println(greenSaucePasta.getPasta())
}
class Pasta {
private lateinit var sauce: Sauce
constructor(sauce: Sauce) {
this.sauce = sauce
}
fun getPasta(): String = "I am pasta with ${sauce.getSauceType()} sauce"
}
interface Sauce {
fun getSauceType(): String
}
class RedSauce : Sauce {
override fun getSauceType(): String = "Red"
}
class WhiteSauce : Sauce {
override fun getSauceType(): String = "White"
}
class GreenSauce : Sauce {
override fun getSauceType(): String = "Green"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment