Created
April 25, 2021 12:11
-
-
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.
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
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()) | |
} |
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
class Pasta { | |
private lateinit var sauce: Sauce | |
constructor(sauce: Sauce) { | |
this.sauce = sauce | |
} | |
fun getPasta(): String = "I am pasta with ${sauce.getSauceType()} sauce" | |
} |
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
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