An example of a factory method pattern in Kotlin.
Table of contents for design patterns in Kotlin
The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time. Wikipedia
Example:
Theme
data class Theme(val name: String, val textColor: String, val backgroundColor: String)
ThemeOption
enum class ThemeOption {
LIGHT,
DARK,
AUTO
}
ThemeFactory
object ThemeFactory {
private val light get() = Theme("Light", "#000000", "#FFFFFF")
private val dark get() = Theme("Dark", "#FFFFFF", "#000000")
private fun auto() = if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) in 0..7) {
dark
} else {
light
}
fun themeFor(themeOption: ThemeOption) = when (themeOption) {
ThemeOption.LIGHT -> light
ThemeOption.DARK -> dark
ThemeOption.AUTO -> auto()
}
}
Usage
fun main() {
val themeLight = ThemeFactory.themeFor(ThemeOption.LIGHT)
val themeDark = ThemeFactory.themeFor(ThemeOption.DARK)
val themeAuto = ThemeFactory.themeFor(ThemeOption.AUTO)
println(Date())
println(themeLight)
println(themeDark)
println(themeAuto)
}
Result
Mon Aug 17 22:33:41 NOVT 2020
Theme(name=Light, textColor=#000000, backgroundColor=#FFFFFF)
Theme(name=Dark, textColor=#FFFFFF, backgroundColor=#000000)
Theme(name=Light, textColor=#000000, backgroundColor=#FFFFFF)