Design Patterns Explained
  • Getting Started
  • SOLID Principles
    • Single Responsibility Principle
    • Open / Closed Principle
    • Liskov Substitution Principle
    • Interface Segregation Principle
    • Dependency Inversion Principle
  • Design Patterns
    • Creational Patterns
      • Abstract Factory Pattern
      • Builder Pattern
      • Factory Pattern
      • Prototype Pattern
      • Singleton Pattern
    • Behavioral Patterns
      • Chain Of Responsibility Pattern
      • Command Pattern
      • Interpreter Pattern
      • Iterator Pattern
      • Mediator Pattern
        • Example 1
      • Memento Pattern
      • Observer Pattern
      • State Pattern
      • Strategy Pattern
        • Example 1
      • Template Method Pattern
      • Visitor Pattern
    • Structural Patterns
      • Adapter Pattern
      • Bridge Pattern
      • Composite Pattern
      • Decorator Pattern
      • Facade Pattern
      • Flyweight Pattern
      • Proxy Pattern
  • Roadmap
Powered by GitBook
On this page
  • Intent
  • When to use
  • Structure
  • Note
  • Examples

Was this helpful?

  1. Design Patterns
  2. Behavioral Patterns

State Pattern

PreviousObserver PatternNextStrategy Pattern

Last updated 4 years ago

Was this helpful?

Sometimes you find yourself in a problem, where an object has a few states that can interchange at anytime, and the object behaves differently according to each state.

Intent

Allow an object to alter its behavior when its internal state changes. The object will appear as if it changed its class.

When to use

  1. When the object's behavior depends on its state and it must change its behavior at run-time depending on the state.

  2. When you have a class polluted with massive conditionals that alter how the class behaves according to the current values of the class’s fields.

  3. When you have a lot of duplicate code across similar states and transitions of a condition-based state machine.

Structure

  • Context: defines the interface of interest to the clients (usually it's directly a class that holds the state).

  • State: defines an interface for encapsulating the behavior associated with a particular state of the Context.

  • ConcreteState: they are the subclasses that implement the different behaviors.

Note

Applying this pattern can be overkill if a state machine has only a few states or rarely changes.

Examples

Source Code

UML

// TODO

You can find the tests .

here
Example 1
Finite-State Machine