State Pattern

State pattern is one of the behavioral design pattern. State design pattern is used when an Object changes its behavior based on its internal state.

If we have to change behavior of an object based on its state, we can have a state variable in the Object and use if-else condition block to perform different actions based on the state.

State pattern is used to provide a systematic and lose-coupled way to achieve this through Context and State implementations.


class Context(var state: State = UnauthorizedState()) {
    var isAuthorized: Boolean = false
        get() = state.isAuthorized(context = this)
    var userId: String? = null
        get() = state.userId(context = this)
    fun changeStateToAuthorized(userId: String) {
        state = AuthorizedState(userId = userId)
    }
    fun changeStateToUnauthorized() {
        state = UnauthorizedState()
    }
}
interface State {
    fun isAuthorized(context: Context): Boolean
    fun userId(context: Context): String?
}
class UnauthorizedState : State {
    override fun isAuthorized(context: Context) = false
    override fun userId(context: Context) = null
}
class AuthorizedState(var userId: String) : State {
    override fun isAuthorized(context: Context) = true
    override fun userId(context: Context) = userId
}
data class Tmp(val i: Int = 0)
fun main(args: Array<String>) {
    val userContext = Context()
    val tmp = Tmp()
    userContext.changeStateToAuthorized(userId = "admin")
    println("${userContext.isAuthorized}, ${userContext.userId}")
    userContext.changeStateToUnauthorized()
    println("${userContext.isAuthorized}, ${userContext.userId}")
}			

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group