State pattern

The state pattern is a behavioral software design pattern to allow an object to alter its behavior when its internal state changes. This pattern is close to the concept of Finite-state machine however it is important to keep in mind that this pattern is not a software implementation of Finite-state machine. The state pattern can be interpreted as a strategy pattern which is able to switch the current strategy through invocations of methods defined in the pattern's interface.

This 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 large monolithic conditional statements[1]:395 and thus improve maintainability.[2]

Overview

The State [3] design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

What problems can the State design pattern solve? [4]

  • An object should change its behavior when its internal state changes.
  • State-specific behavior should be defined independently. That is, new states should be added and the behavior of existing states should be changed independently.

Implementing state-specific behavior directly within a class is inflexible because it commits the class to a particular behavior and makes it impossible to add a new state or change the behavior of an existing state later independently from (without changing) the class.

What solution does the State design pattern describe?

  • Define separate (state) objects that encapsulate state-specific behavior for each state. That is, define an interface (State) for performing state-specific behavior, and define classes that implement the interface for each state.
  • A class delegates state-specific behavior to its current state object instead of implementing state-specific behavior directly.

This makes a class independent of how state-specific behavior is implemented. New states can be added by defining new state classes.
A class can change its behavior at run-time by changing its current state object.

See also the UML class and sequence diagram below.

Structure

UML class and sequence diagram

In the above 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.

Class diagram

State in UML[1][6]
State in LePUS3[6][7]

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 Statelike {
    void writeName(StateContext context, String name);
}

class StateLowerCase implements Statelike {
    @Override
    public void writeName(final StateContext context, final String name) {
        System.out.println(name.toLowerCase());
        context.setState(new StateMultipleUpperCase());
    }
}

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

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

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

class StateContext {
    private Statelike myState;
    StateContext() {
        setState(new StateLowerCase());
    }

    /**
     * Setter method for the state.
     * Normally only called by classes implementing the State interface.
     * @param newState the new state of this context
     */
    void setState(final Statelike newState) {
        myState = newState;
    }

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

The demonstration below shows the usage:

public class DemoOfClientState {
    public static void main(String[] args) {
        final StateContext sc = new StateContext();

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

With the above code, the output of main() from DemoOfClientState should be:

monday
TUESDAY
WEDNESDAY
thursday
FRIDAY
SATURDAY
sunday

See also

References

  1. 1 2 Erich Gamma, Richard Helm, Ralph Johnson, John M. Vlissides (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN 0-201-63361-2.
  2. Jaeger, Thomas. "The State Design Pattern vs. State Machine". www.codeproject.com. CodeProject. Retrieved 5 May 2015.
  3. Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 305ff. ISBN 0-201-63361-2.
  4. "The State design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-12.
  5. "The State design pattern - Structure and Collaboration". w3sDesign.com. Retrieved 2017-08-12.
  6. 1 2 State pattern in UML and in LePUS3
  7. legend
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.