Pattern: State

Synopsis

The State pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class. The State pattern switches between internal classes in such a way that the enclosing object appears to change its class.

Context

Many objects are required to have a dynamically changing set of attributes called their state. Such objects are called stateful objects. An object’s state will usually be one of a predetermined set of values. When a stateful object becomes aware of an external event, its state may change. The behavior of a stateful object is determined by its state.

Forces

Solution

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 particular state of the Context.

ConcreteState subclasses

    – each subclass implements a behavior associated with a state of the Context

 

 

Consequences

Implementation

The code example implements an Appointment Calendar system. The abstract class State implements two methods: Edit and Save. The two concrete state classes are Clean State and Dirty State. The Appointment Calendar system is in the Clean State when no changes have been made to it since the last Save. The Appointment Calendar system is in the Dirty State when there have been changes since the last Save. Depending on the current state and the input from the user (Edit or Save), the next state is set to Clean or Dirty.

 

Related Patterns


Modified: 6-Apr-2004
Sowmya Narayanan