Last updated
Last updated
Usage examples: The State pattern is commonly used in Java to convert massive switch
-base state machines into objects.
Here are some examples of the State pattern in core Java libraries:
(controlled by the : behavior is dependent on current phase (state) of JSF lifecycle)
Identification: The State pattern can be recognized by methods that change their behavior depending on the objects’ state. You can confirm identification if you see that this state can be controlled or replaced by other objects, including state objects themselves.
In this example, the State pattern lets the same media player controls behave differently, depending on the current playback state. The main class of the player contains a reference to a state object, which performs most of the work for the player. Some actions may end-up replacing the state object with another, which changes the way the player reacts to the user interactions.
states/State.java: Common state interface
states/LockedState.java
states/ReadyState.java
states/PlayingState.java
ui/Player.java: Player primary code
ui/UI.java: Player’s GUI
Demo.java: Initialization code
OutputDemo.png: Screenshot