![]() |
VOOZH | about |
State method is Behavioral Design Pattern that allows an object to change its behavior when there occurs a change in its internal state. It helps in implementing the state as a derived class of the state pattern interface. If we have to change the 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. It may be termed as the object-oriented state machine. It implements the state transitions by invoking methods from the pattern's superclass.
The State method pattern represents the Finite State Machine.
At any moment, there can be a finite no. of states that can be present in the program. Each and every state is unique in their kind of behavior and other things. Even the program can change itself from one state to another at any moment of time. A program can go from one state to another if and only if the required transition is available in rules. It will certainly become difficult when we add a large number of states. It will become difficult to handle the code as any small change in transition logic may lead to a change in state conditionals in each method. =
Let's have a look at the solution to the above-described problem by considering the example of Radio. Here the radio has two states named as Am State and FM State. We can use the switch to toggle between these two states. The State method suggests that we should create a new class for all possible states of an object and extract all state-specific behaviors into these classes. Instead of implementing all behaviors on its own, the original object called context, stores a reference to one of the state objects that represents its current state, and represents all the state-related work to that object.
Visiting... Station is 89.1 FM
Visiting... Station is 103.9 FM
Visiting... Station is 81.3 FM
Switching to AM
Visiting... Station is 1380 AM
Visiting... Station is 1510 AM
Visiting... Station is 1250 AM
Visiting... Station is 1380 AM
Visiting... Station is 1510 AM
Visiting... Station is 1250 AM
Switching to FM
Visiting... Station is 89.1 FM
Visiting... Station is 103.9 FM
Visiting... Station is 81.3 FM
Following is the UML diagram for the state method
Further Read - State Method in Java