Design Pattern | State Pattern

What Is the State Pattern?

  • State means condition or state.
  • The State pattern expresses states as classes and represents state changes by switching classes.
  • In GoF design patterns, it is classified as a behavioral design pattern.

State Pattern Example Program

The example is a safe management program that changes button behavior depending on whether it is day or night.

Class Diagram
State Pattern Class Diagram

The example defines a Context interface for managing the safe’s state and communicating with the security center, a State interface for behavior in each state, concrete day and night states, and a UI context that delegates behavior to the current state.

Advantages

State-specific behavior is collected in state classes instead of being scattered through conditionals. Adding or changing states becomes easier, and the context can remain focused on state transitions and delegation.