I've been a zone leader with DZone since 2008, and I'm crazy about community. Every day I get to work with the best that JavaScript, HTML5, Android and iOS has to offer, creating apps that truly make at difference, as principal front-end architect at Avego. James is a DZone Zone Leader and has posted 639 posts at DZone. You can read more from them at their website. View Full User Profile

Design Patterns Uncovered: The State Pattern

  • submit to reddit
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 playe.

public class MP3PlayerContext
private State state;

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

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.

Other Articles in This Series
The Observer Pattern
The Adapter Pattern
The Facade Pattern
The Factory Method Pattern
The Abstract Factory Pattern
The Singleton Pattern
The Strategy Pattern
The Visitor Pattern

The Decorator Pattern
The Proxy Pattern
The Command Pattern
The Chain of Responsibility Pattern
The Interpreter Pattern

Next Up

Just one pattern left now - The Builder Pattern. We'll be covering that in the next few days.



nilesh gule replied on Thu, 2012/07/12 - 10:28am

Nice illustration of State design pattern. I recently wrote about State pattern as well using Personal loan as an example. Due to similarities between C# & Java people might find it interesting http://www.nileshgule.com/2012/07/state-design-pattern.html

Manoj Kumar replied on Thu, 2013/09/26 - 12:21pm

 State design pattern works on the concept of state change. Entire process life-cycle can be divided in multiple phases.With completion of each phase process exits from one state and enters in to another state.

For example In JSF framework entire web request response lifecycle is divided in six phases:

After completion of every phase process exits from a state and enters into another state. For example after RestoreValuePhase we can say ViewRestored as exit state and RequestApply as entering state .

So to implement State design pattern It is required to divide entire process in such a way that It can be processed in multiple phases with every phase exit defining a state change.

Now let's understand this with below code.

Any project lifecycle can be divided in multiple phases like


So these are the phases used in below example

Rules :

1. We need to define a class where we can store the current state of the process. NextPhase class in below code is doing that.

2. We need to define an Interface wherein we can provide the contact method that would be implemented in each phase.In below code ProjectPhase is doing that.

Learn more about State design pattern here  -- <a href="http://efectivejava.blogspot.in/2013/09/java-state-design-patten-oops-state.html?utm_source=BP_recent">State Design Pattern</a>


Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.