behavioral

State

Allow an object to alter its behavior when its internal state changes by delegating state-specific behavior to separate state objects.

Problem

behavioral

An object behaves differently depending on its internal state, and conditional logic is becoming hard to manage.

Integration notes

State is useful for workflows, media players, order lifecycles, and any domain where behavior changes as the object moves through a lifecycle.

Tradeoffs

  • Can introduce many small classes if the state graph is large
  • State transitions may become harder to trace if spread across multiple classes

Languages

typescript, java, python, angular, react, react-native, csharp, dotnet

Platforms

Web, Backend, Mobile, UI kits, Cross-platform systems

Variants

Scenarios

Order state

An order changes behavior as it moves from pending to processing to shipped.

Language examples

Core languages

Frameworks and libraries

Order statetypescript

The order object delegates state-dependent behavior to separate state classes, which makes lifecycle transitions easier to extend.

TypeScript
interface OrderState {
  next(order: Order): void;
  name(): string;
}


class Order {
  private state: OrderState;


  constructor() {
    this.state = new PendingState();
  }


  setState(state: OrderState): void {
    this.state = state;
  }


  proceed(): void {
    this.state.next(this);
  }


  getStateName(): string {
    return this.state.name();
  }
}


class PendingState implements OrderState {
  next(order: Order): void {
    order.setState(new ProcessingState());
  }


  name(): string {
    return "Pending";
  }
}


class ProcessingState implements OrderState {
  next(order: Order): void {
    order.setState(new ShippedState());
  }


  name(): string {
    return "Processing";
  }
}


class ShippedState implements OrderState {
  next(order: Order): void {
    console.log("Order already shipped");
  }


  name(): string {
    return "Shipped";
  }
}


const order = new Order();
console.log(order.getStateName());
order.proceed();
console.log(order.getStateName());
order.proceed();
console.log(order.getStateName());
order.proceed();

Real-world examples

  • Order lifecycles: Orders often move through pending, processing, shipped, delivered, and canceled states.
  • Traffic systems: Traffic lights and crossing signals change behavior based on their current phase.
  • Media controls: Music and video players expose different actions depending on playback state.