State Pattern Tutorial with Java Examples
Learn the State Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
Join the DZone community and get the full member experience.
Join For FreeToday'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. Thedefinition of State provided in the original Gang of Four book on DesignPatterns 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.
//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.
Next Up
Just one pattern left now - The Builder Pattern. We'll be covering that in the next few days.
Enjoy the Whole "Design Patterns Uncovered" Series:
Creational Patterns
- Learn The Abstract Factory Pattern
- Learn The Builder Pattern
- Learn The Factory Method Pattern
- Learn The Prototype Pattern
Structural Patterns
- Learn The Adapter Pattern
- Learn The Bridge Pattern
- Learn The Decorator Pattern
- Learn The Facade Pattern
- Learn The Proxy Pattern
Behavioral Patterns
- Learn The Chain of Responsibility Pattern
- Learn The Command Pattern
- Learn The Interpreter Pattern
- Learn The Iterator Pattern
- Learn The Mediator Pattern
- Learn The Memento Pattern
- Learn The Observer Pattern
- Learn The State Pattern
- Learn The Strategy Pattern
- Learn The Template Method Pattern
- Learn The Visitor Pattern
Opinions expressed by DZone contributors are their own.
Comments