GofPatterns Gofpatterns





Behavioral Patterns  «Prev  Next»

State Pattern

The State pattern allows an object to alter its behavior when its internal state changes. The object appears to change its class.
The Figure illustrates the State Pattern.

StateContext aggregates abstract State. ConcreteStateA and ConcreteStateB inherit from abstract State.
StateContext aggregates abstract State. ConcreteStateA and ConcreteStateB inherit from abstract State.


Benefits:
The following lists the benefits of using the State pattern:
  1. Localizes state-specific behavior and partitions behavior for different states .
  2. Make state transitions explicit.
When to Use:
You should use the State pattern when:
  1. An object's behavior depends on its state and it must change its behavior at run-time depending on that state.
  2. Operations have large conditional statements that consist of multiple states and depend on the object's state.