State behavioral design pattern with previous state

I am always interested in utilizing design patterns in my development tasks.  I finally had the need to check if the state of something changed from it’s previous state.  I thought this would be the perfect use of the state design pattern.  I made a small modification but it worked perfectly.

I followed the java example from and changed a few things to fit my needs. The complete code and tests are here:

In order to get the previous state I modified the context class:

public class StateContext {
	private Statelike currentState;
	private Statelike previousState;

	public Statelike getCurrentState() {
		return currentState;

	StateContext() {
		setState(new StateOther());

	void setState(final Statelike newState) {
		previousState = currentState;
		currentState = newState;

	public boolean isStateChanged(){
		return !(previousState.getClass().equals(currentState.getClass()));

	public void setMode(final String mode) {
		currentState.setMode(this, mode);

Example of tests:

testOpenOpen – the state never changes
testOpenOther – the state changed

public void testOpenOpen() {
	final StateContext sc = new StateContext();
	assertTrue(sc.getCurrentState() instanceof StateOpen);

public void testOpenOther() {
	final StateContext sc = new StateContext();
	assertTrue(sc.getCurrentState() instanceof StateOther);
Tagged with: ,
Posted in Design Patterns, Java

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: