March 23rd, 2011 | by matthew |
Here’s the somewhat maligned GOF State Pattern. This allows us to localise state specific behaviour into a single subclass for each state. The State interface defines the behaviour that each concrete State class must implement. Here’s a simple example. (We’re all familiar with traffic lights!)

That’s it! What a state!
Got more than one minute? OK, lets go into a bit more detail. The context object only ever references a single concrete State object to which it delegates state specific activity. This ensures that state transitions are atomic. The transitions between states can be managed by the Context, or (my preference) this control can be delegated to the State objects themselves.
How about some code.
Here’s the State interface.
public interface TrafficLightState {
public TrafficLightState transition();
public Light[] illuminate();
}
Here’s the an example of a concrete State class, representing the Stop state. See how it defines the following state in its transition method. The illuminate method defines the state specific behaviour, in this case which lights should be turned on.
public class StopState implements TrafficLightState {
public TrafficLightState transition() {
return new ReadyGoState();
}
public Light[] illuminate() {
return new Light[]{Light.red, Light.greenWalkingMan};
}
}
And here’s the context class.
public class TrafficLightContext {
private TrafficLightState state;
public TrafficLightContext() {
state = new StopState();
}
public void run() {
for (;;) {
try{
for (Light light : state.illuminate()){
System.out.print(light.name()+" ");
}
Thread.sleep(2000);
state = state.transition();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TrafficLightContext context = new TrafficLightContext();
context.run();
}
}
Alternatively, the State objects could be passed a reference to the Context object so that they could access contextual data and modify the Context’s State at whatever point is appropriate.




Sorry, comments for this entry are closed at this time.