7 State (Behavioral) Design Pattern

The State Design Pattern is a behavioral design pattern that allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

Intent

  • Allow an object to change its behavior dynamically based on its state.
  • Remove complex conditionals (like if-else or switch statements) that depend on an object's state.

Key Components

  1. Context: The main object that contains a state. It delegates state-specific behavior to the current state object.
  2. State Interface: An interface that defines the behavior associated with a particular state.
  3. Concrete State: Implementations of the state interface that define specific behaviors for each state.

When to Use

  • When an object’s behavior depends on its state, and it must change its behavior dynamically at runtime.
  • When you want to avoid multiple conditional statements that determine the object’s behavior based on its state.