Jump to content

State pattern

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by RacoonyRE (talk | contribs) at 13:46, 4 April 2021 (Reverted edits by ClueBot_NG (talk) (HG) (3.4.10)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern's interface.

The state pattern is used in computer programming to encapsulate varying behavior for the same object, based on its internal state. This can be a cleaner way for an object to change its behavior at runtime without resorting to conditional statements and thus improve maintainability.[1]: 395 

haha car go brrrrrr

Structure

State in UML[1]

In the accompanying Unified Modeling Language (UML) class diagram, the Context class doesn't implement state-specific behavior directly. Instead, Context refers to the State interface for performing state-specific behavior (state.operation()), which makes Context independent of how state-specific behavior is implemented. The State1 and State2 classes implement the State interface, that is, implement (encapsulate) the state-specific behavior for each state. The UML sequence diagram shows the run-time interactions:

The Context object delegates state-specific behavior to different State objects. First, Context calls operation(this) on its current (initial) state object (State1), which performs the operation and calls setState(State2) on Context to change context's current state to State2. The next time, Context again calls operation(this) on its current state object (State2), which performs the operation and changes context's current state to State1.

Example

Java

The state interface and two implementations. The state's method has a reference to the context object and is able to change its state.

interface State {
    void writeName(StateContext context, String name);
}

class LowerCaseState implements State {
    @Override
    public void writeName(StateContext context, String name) {
        System.out.println(name.toLowerCase());
        context.setState(new MultipleUpperCaseState());
    }
}

class MultipleUpperCaseState implements State {
    /* Counter local to this state */
    private int count = 0;

    @Override
    public void writeName(StateContext context, String name) {
        System.out.println(name.toUpperCase());
        /* Change state after StateMultipleUpperCase's writeName() gets invoked twice */
        if (++count > 1) {
            context.setState(new LowerCaseState());
        }
    }
}

The context class has a state variable that it instantiates in an initial state, in this case LowerCaseState. In its method, it uses the corresponding methods of the state object.

class StateContext {
    private State state;
    
    public StateContext() {
        state = new LowerCaseState();
    }

    /**
     * Set the current state.
     * Normally only called by classes implementing the State interface.
     * @param newState the new state of this context
     */
    void setState(State newState) {
        state = newState;
    }

    public void writeName(String name) {
        state.writeName(this, name);
    }
}

The demonstration below shows the usage:

public class StateDemo {
    public static void main(String[] args) {
        StateContext context = new StateContext();

        context.writeName("Monday");
        context.writeName("Tuesday");
        context.writeName("Wednesday");
        context.writeName("Thursday");
        context.writeName("Friday");
        context.writeName("Saturday");
        context.writeName("Sunday");
    }
}

With the above code, the output of main() from StateDemo is:

 monday
 TUESDAY
 WEDNESDAY
 thursday
 FRIDAY
 SATURDAY
 sunday

References

  1. ^ a b Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. 1995. ISBN 0-201-63361-2. {{cite book}}: Unknown parameter |authors= ignored (help)