Skip to content

Week 13 - State Design Pattern

The State Design Pattern

Classification

  • Behavioral Design Pattern

Pattern Definition

  • Hard Definition: Allow an Object to alter its behavior when its internal state changes. The object will appear to change its class.
  • Easy Definition: Allows an Object to change its behavior via a state object.

Representations

Mermaid Graph - State Pattern

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
classDiagram
    State <|.. ConcreteStateA
    State <|.. ConcreteStateB
    State --* Context
    Client --> Context
    class State {
        <<interface>>
        +handle()
    }
    class ConcreteStateA{
      -Context context
      +handle()
    }
    class ConcreteStateB {
      -Context context
      +handle()
    }
    class Context{
      -State state
      +request(): "state.handle()"
    }
    class Client {
        -Context context
    }

UML

When to use

  • You have an object that needs to have different behavior depending on its current state. Use it when the number of states is enormous, and your code frequently changes depending on the state.
  • You can use the State pattern when you have a class filled with many conditions that control or alter how the class behaves according to the current values of the class fields. How you refactor to the State pattern is that you extract conditional branches into separate state classes. By doing that, you can separate the state-specific code from the main class.
  • You can also use the State pattern if you have a lot of transitions between different classes’ states

Real World Usages

  • TCP/IP Connection: The TCP Connection can be in one of several states, TCP Established, TCP Listen, TCP Closed, etc. Thus, the State Pattern is used to transition and report the state of the connection.
  • Other Stateful protocols.

Java Code Example

Main Take-Aways from the textbook

  • The State Pattern allows an object to have many different behaviors that are based on its internal state (Polymorphism).
  • Unlike a procedural state machine, the State Pattern represents each state as a full-blown class.
  • The Context gets its behavior by delegating to the current state object it is composed with.
  • By encapsulating each state into a class, we localize any changes that will need to be made.
  • The State and Strategy Patterns have the same class diagram, but they differ in intent.
  • The Strategy Pattern typically configures Context classes with a behavior or algorithm.
  • The State Pattern allows Context to change its behavior as the state of the Context changes.
  • State transitions can be controlled by the State classes or by the Context classes.
  • Using the State Pattern will typically result in a greater number of classes in your design.
  • State classes may be shared among Context instances.

Main OO Principles of State Pattern