An example of a facade pattern in Kotlin.
Table of contents for design patterns in Kotlin
The facade pattern (also spelled façade) is a software-design pattern commonly used in object-oriented programming. Analogous to a facade in architecture, a facade is an object that serves as a front-facing interface masking more complex underlying or structural code. Wikipedia
Example:
Preferences
class Preferences {
private val store = hashMapOf<String, String>()
fun getString(key: String): String? = store.get(key)
fun putString(key: String, value: String) = store.put(key, value)
fun commit() = println("Commit")
}
ApplicationSettings
class ApplicationSettings(
private val preferences: Preferences
) {
fun setTheme(theme: String) = with(preferences) {
putString(KEY_THEME, theme)
commit()
}
fun setTimeLimit(time: Long) = with(preferences) {
putString(KEY_TIME_LIMIT, time.toString())
commit()
}
fun getTheme(): String = preferences.getString(KEY_THEME) ?: DEFAULT_TIME
fun getTimeLimit(): Long = preferences.getString(KEY_TIME_LIMIT)?.toLong() ?: DEFAULT_TIME_LIMIT
companion object {
private const val KEY_THEME = "app_theme"
private const val KEY_TIME_LIMIT = "app_time_limit"
private const val DEFAULT_TIME = "light"
private const val DEFAULT_TIME_LIMIT = 10_000L
}
}
Usage
fun main() {
val preferences = Preferences()
val applicationSettings = ApplicationSettings(preferences)
with(applicationSettings) {
println(getTheme())
println(getTimeLimit())
setTheme("dark")
setTimeLimit(12345)
println(getTheme())
println(getTimeLimit())
}
}
Result
light
10000
Commit
Commit
dark
12345