java-design-patterns
This article will be about State design pattern. It is one of behavioral design patterns. You don’t need to know many theory to understand the main concepts of the pattern. The post will be break in several parts where I will provide information about situations where the pattern need to be applied, cons and pros which it has and an example of usage.

Sometimes you need to change a behavior of object when its internal state changes. The State design pattern allows to do this. You can obtain this by creation of separate classes which represent different states and functionality. Of Course these classes have to be inherited from one abstract class or implement one interface.

The State design pattern can be used when we need to change state of object at runtime by inputting in it different subclasses of some State base class. This circumstance is advantage and disadvantage in the same time, because we have a clear separate State classes with some logic and from the other hand the number of classes grows up.

Let’s consider the example. Each year has 4 seasons: Winter, Spring, Summer and Autumn.Each season has its own order, e.g. Spring comes after Winter, Summer comes after Spring and so on.

Base state interface for the seasons:

public interface Season {
	public void theSeason(SeasonContext context);
}

State Design Pattern

State classes which implement the Season interface:

public class Winter implements Season {

	@Override
	public void theSeason(SeasonContext context) {
		System.out.println("Winter is now.");
		context.setSeason(new Spring());
	}

}

Spring class:

public class Spring implements Season {

	@Override
	public void theSeason(SeasonContext context) {
		System.out.println("Spring is now");
		context.setSeason(new Summer());
	}

}

I’ll omit classes for Summer and Autumn, because they are the same as previous classes.
The SeasonContext class:

public class SeasonContext {
	private Season season;
	
	public SeasonContext() {
		this.season = new Winter();
	}
	
	public void setSeason(Season season) {
		this.season = season;
	}
	
	public void whatTheSaeson() {
		season.theSeason(this);
	}
}

All this stuff shows architecture of the State pattern: base state interface, classes which implement the state interface and the state context. Now let’s see how it works:

...
	public static void main(String[] args) {
		SeasonContext sc = new SeasonContext();
		sc.whatTheSaeson();
		sc.whatTheSaeson();
		sc.whatTheSaeson();
		sc.whatTheSaeson();
	}
...

The result will be:

Winter is now.
Spting is now
Summer is now.
Autumn is now.

Don’t forget to follow us on FaceBook.

About The Author

Mathematician, programmer, wrestler, last action hero... Java / Scala architect, trainer, entrepreneur, author of this blog

Close