Skip to content
Roberto Fronteddu edited this page Mar 1, 2023 · 2 revisions

The State is a Behavioral Design Pattern. This pattern allows our objects to behave differently based on their current internal state and to define the behaviors in separate classes. Each state the object can be in becomes a different class.

Usefull when

  • We want to add new states and behaviors without changing our main class.

UML

state uml

  • Context: Class whose state is now an object. Client code works with this class. Delegates operations to the current state.
  • State: Defines the operations called by the owning object
  • ConcreteStateA/B: Represent a particular state of an object, and implements behavior specific to this state value.

Implementation steps

  1. Identify distinct values for the state of our object (context)
    • Each state value will be a separate class in our implementation.
    • These classes will provide behavior specific to the state value they represent.
  2. In the main/context class method implementations, we will delegate the operation to the current state object.
  3. Decide how state transition happens
    • States can transition themselves to the next state based on inputs
    • The context initiates the transition
  4. Client interacts with the main class/context and is unaware of the existence of the state.

Design Considerations

  • If the state object does the state transitions, the state object has to know about at least one state. This adds to the amount of code change needed when adding new states.
  • Using the flyweight pattern we can share the states with no instance variables.
  • State pattern is not the same as a state machine. A state machine focuses on state transitions based on input values and uses a table to map these inputs to states, a state design pattern focuses on providing a behavior specific to a state value of a context object.

Comparison with Command

State

  • Implements the actual behavior of an object specific to a particular state.
  • A state object represents the current state of our context object.

Command

  • Command execution simply calls a specific operation on a receiver.
  • Command represents an operation or request, It does not have any direct relation to the state of the receiver.

Pitfalls

  • Classes grow with the number of states.
  • State transition can become tricky
  • We may not be able to plan for all the required states at design time.

Real-Life Examples

  • JSF (java server faces) framework's LifeCycle implementation. The LifeCycle instance collaborates with multiple "phases" to execute a JSF request. Each phase represents a state in the state pattern design.
Clone this wiki locally