Skip to content

Instantly share code, notes, and snippets.

@markmaynard
Last active June 10, 2019 11:45
Show Gist options
  • Save markmaynard/b526f4b5515ea41c4870e27cb1f4411d to your computer and use it in GitHub Desktop.
Save markmaynard/b526f4b5515ea41c4870e27cb1f4411d to your computer and use it in GitHub Desktop.
Generic Singleton Factory part 1 complete
val factory = ThingFactory()
factory.run<Thing1>() // "Run Fast!"
factory.play<Thing1>() // "Play Hard!"
factory.play<Thing2>() // "Play Hard!" ????
interface SomeThing {
fun run()
fun play()
}
class Thing1: SomeThing {
override fun run() = println("Run Fast!")
override fun play() = println("Play Hard!")
}
class Thing2: SomeThing {
override fun run() = println("Run Silly!")
override fun play() = println("Play Soft!")
}
class ThingFactory {
inline fun <reified T: Any> run() {
if (myThing == null) {
createThing<T>()
}
myThing!!.run()
}
inline fun <reified T: Any> play() {
if (myThing == null) {
createThing<T>()
}
myThing!!.play()
}
inline fun <reified T: Any> createThing() {
when(T::class) {
Thing1::class -> myThing = Thing1()
Thing2::class -> myThing = Thing2()
else -> throw IllegalArgumentException("Unknown thing")
}
}
companion object {
var myThing: SomeThing? = null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment