Design Patterns Uncovered: The State Pattern

Today’s pattern is the State pattern, which allows objects to behave in different ways depending on internal state. State is used when you need a class to behave differently, such as performing slightly different computations, based on some arguments passed through to the class.

State in the Real World

Vending machines maintain an internal state which allow it to change it’s behaviour accordingly. For example, if there is no change available, it will demand exact change. When something is out of stock, it will deliver none of that product.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The State Pattern

The State pattern is known as a behavioural pattern – it’s used to manage algorithms, relationships and responsibilities between objects. The definition of State provided in the original Gang of Four book on Design Patterns states:

Allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.

Let’s take a look at the diagram definition before we go into more detail.

The Context can have a number of internal States, whenever the request() method is called on the Context, the message is delegated to the State to handle. The State interface defines a common interface for all concrete states, encapsulating all behaviour associated with a particular state. The ConcreteState implements it’s own implementation for the request. When a Context changes state, what really happens is that we have a different ConcreteState associated with it.

This is all quite similar to the Strategy pattern, except the changes happen at runtime rather than the client deciding. State saves you from lots of conditional code in your Context: by changing the ConcreteState object used, you can change the behaviour of the context.

Would I Use This Pattern?

You should use the State pattern when the behaviour of an object should be influenced by it’s state, and when complex conditions tie object behaviour to it’s state.

So How Does It Work In Java?

We’ll use the state of an mp3 player to give an example of the state pattern in action. First we set up a context for our mp3 player.

//Context
public class MP3PlayerContext
{
	private State state;

	private MP3PlayerContext(State state)
	{
	   this.state= state;
	}
	public void play()
	{
		state.pressPlay(this);
	}

	public void setState(State state)
	{
		this.state = state;
	}

	public State getState()
	{
		return state;
	}

}

Now we’ll create our state interface. In this example, we’ve just got a play button.

private interface State
{
	public void pressPlay(MP3PlayerContext context);
}

And finally, creating a state for Standby and for Playing.

public class StandbyState implements State
{
	public void pressPlay(MP3PlayerContext context)
	{
		context.setState(new PlayingState());
	}

}

public class PlayingState implements State
{
	public void pressPlay(MP3PlayerContext context)
	{
		context.setState(new StandbyState());
	}

}

So this shows how the state pattern works at a simple level. Of course, our pressPlay methods would do more than simply set the state of the context.

Watch Out for the Downsides

There are some potential bad uses of the state pattern. For example, some operations may not be possible when the context is in certain states. This article proposes a nice solution to the problem

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>