An example of a state pattern in Kotlin.
Table of contents for design patterns in Kotlin
The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern’s interface. Wikipedia
Example:
AuthorizationState
sealed class AuthorizationState
object Unauthorized : AuthorizationState()
class Authorized(val userName: String) : AuthorizationState()
AuthorizationModel
class AuthorizationModel {
private var state: AuthorizationState = Unauthorized
val isAuthorized: Boolean
get() = when (state) {
is Authorized -> true
is Unauthorized -> false
}
val userName: String
get() = this.state.let {
when (it) {
is Authorized -> it.userName
is Unauthorized -> "Unknown"
}
}
fun login(userName: String) {
state = Authorized(userName)
}
fun logout() {
state = Unauthorized
}
}
Usage:
fun main() {
val model = AuthorizationModel()
println("${model.isAuthorized} ${model.userName}")
model.login("admin")
println("${model.isAuthorized} ${model.userName}")
}
Result
false Unknown
true admin