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);
}
Leave a comment