State

According to the state pattern, we should implement each state of a system as a derived object. We should also declare a class that contains a property that represents the current state and methods that invoke transitions between states. It's worth mentioning that we can consider the state pattern as an extension of the Strategy pattern because methods can change their behavior depending on the state. The following diagram shows what an implementation of this pattern may look like:

The diagram contains classes such as UnauthorizedState, ProfileCompletedState, and SignedUpState, which all represent a certain state of a program. These classes implement the AuthorizationState interface that's encapsulated by the AuthorizationContext class.

AuthorizationState is a sealed class that restricts the hierarchy of states:

sealed class AuthorizationState

The following classes represent states:

class SignedUpState: AuthorizationState()

class ProfileCompletedState: AuthorizationState()

class UnauthorizedState: AuthorizationState()

The AuthorizationContext class encapsulates the current state and contains methods that perform transitions between states:

class AuthorizationContext {
var state: AuthorizationState = UnauthorizedState()

fun signUp() {
state = SignedUpState()
}

fun completeProfile() {
state = ProfileCompletedState()
}

fun display() = when (state) {
is UnauthorizedState -> println("Display sign up screen")
is SignedUpState -> println("Display complete profile screen")
is ProfileCompletedState -> println("Display main screen")
}

override fun toString(): String {
return "AuthorizationContext(state=$state)"
}
}

Use of this code may look like this:

fun main(args: Array<String>) {
val context = AuthorizationContext()
context.display()
context.signUp()
println(context)
context.display()
context.completeProfile()
println(context)
}

The output is as follows:

Display sign up screen
AuthorizationContext(state=chapter6.patterns.behavioral.SignedUpState@2626b418)
Display complete profile screen
AuthorizationContext(state=chapter6.patterns.behavioral.ProfileCompletedState@5a07e868)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.253.31