terminal

codeando_simple

terminal

menu

terminal

search_module

guest@codeandosimple: ~/system/search $ grep -r "" .

Press [ENTER] to execute search

Status

Engine: Ready

Database: Online

Index: V2.1.0_LATEST

bash -- cat state.md
guest@codeandosimple: ~/blog/design-patterns $ cat state.md

State Pattern_

// "Let every academic challenge be an opportunity to demonstrate your ability and growth. Face your studies with courage and determination, because every achievement begins with the courage to try" - George Saville

# Purpose

The State pattern allows an object to alter its behavior when its internal state changes. It encapsulates variable states as independent objects.

# Problem

  • Variable Behavior: The object must act differently depending on its state at runtime.

  • Complex Conditionals: Avoid massive if/switch statements that depend on state variables.

# Solution

Create separate classes for each state. The main object (Context) delegates execution to the current state object.

# Structure

State UML Structure

# Participants

  • Context: Maintains the reference to the current state and delegates tasks.
  • State (Interface): Defines the interface for the states.
  • ConcreteState: Specific implementation of each behavior.

# When to Use It

When an object has clearly identifiable states that drastically alter its behavior in response to the same method calls.

# Advantages

  • verified

    Single Responsibility: Logic for each state is isolated.

  • verified

    Open/Closed: Easy to add new states without touching the context.

# Disadvantages

  • warning

    Class Explosion: Many states mean many files.

  • warning

    Overkill: Unnecessary for objects with few simple states.

# Example: Traffic Light

Management of Red, Yellow and Green states with automatic transition rules.

State Traffic Light Example

# Java Code

interface State { void handle(Context c); }

class GreenState implements State {
    public void handle(Context c) {
        System.out.println("Green light");
        c.setState(new YellowState());
    }
}

class Context {
    private State state = new GreenState();
    public void change() { state.handle(this); }
}

# Mapping Participants

  • TrafficLightState: State Interface.
  • RedState/GreenState: ConcreteStates.
  • TrafficLightContext: Context.

# Conclusions

It eliminates the need for tangled conditionals and makes the transition flow explicit and easy to audit.

# Related Patterns

Strategy

Both use delegation, but State changes according to the internal state.