State

State

Intent

Allow an object to alter it's hebavior when it's interna; state changes. The object will appear to change it's class.

Also known as

Objects for States.

Applicability

Use ths State pattern in either of the folowing cases:

  • An object's behavior depends on it's state, and it must change it's behavior at run-time depending on that state.
  • Operations have large, multipart conditional statements that depend on the object's state.

Structure

Orange

Participants

  • Context: defines the interface of interest to clients, maintains an instance of a ConcreteState subclass that defines the current state.
  • State: defines an interface for encapsulating the behavior associated with a particvular state of the Context.
  • ConCreteState subclass: each subclass implements a behavior associated with a state of the Context.

Collaborations

  • Context delegates state-specific requests to the current ConcreteState object.
  • A context may pass itself as an argument to the State object handling the request. This lets the State object access thee context if necessary.
  • Context is the primary interface for clients. Clients can configure a context with State objects. Once a context is configured, it's clients don't have to deal with the State objects directly.
  • Either Context or the ConcreteState subclasses can decided which state succeeds another and under what circumstances.

Consequences

The State pattern has following consequences:

  • It localizes state-specific behavior and partitions behavior for different states.
  • It makes state transitions explicit.
  • State objects can be shared.

Sample Code

State

Related Patterns

  • The Flyweight pattern explains when and how State objects can be shared.
  • State objects are often Singletons.