Java

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:

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.

Interface of a media player

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

states/State.java: Common state interface

package refactoring_guru.state.example.states;

import refactoring_guru.state.example.ui.Player;

/**
 * Common interface for all states.
 */
public abstract class State {
    Player player;

    /**
     * Context passes itself through the state constructor. This may help a
     * state to fetch some useful context data if needed.
     */
    State(Player player) {
        this.player = player;
    }

    public abstract String onLock();
    public abstract String onPlay();
    public abstract String onNext();
    public abstract String onPrevious();
}

states/LockedState.java

states/ReadyState.java

states/PlayingState.java

ui

ui/Player.java: Player primary code

ui/UI.java: Player’s GUI

Demo.java: Initialization code

OutputDemo.png: Screenshot

Last updated