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 http://en.wikipedia.org/wiki/State_pattern and changed a few things to fit my needs. The complete code and tests are here: https://github.com/abefarris/stateDesignPattern

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

@Test
public void testOpenOpen() {
	final StateContext sc = new StateContext();
	sc.setMode("open");
	sc.setMode("open");
	assertFalse(sc.isStateChanged());
	assertTrue(sc.getCurrentState() instanceof StateOpen);
}

@Test
public void testOpenOther() {
	final StateContext sc = new StateContext();
	sc.setMode("open");
	sc.setMode("other");
	assertTrue(sc.isStateChanged());
	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:

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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: