Background
I have a command that uses the state pattern. When the command state changes I am notified in the UI that for example class stageOneState is now the active state. Is it bad practice to check the state class type using a string as an identifier? Is this undoing the work of the state pattern?
What would be an alternative?
Example
if (notifiedState.type == "state1") {
// Update UI accroding to state1
} else ...
Example
Example from http://www.tutorialspoint.com/design_pattern/state_pattern.htm
public interface State {
public void doAction(Context context);
}
public class StartState implements State {
public void doAction(Context context) {
System.out.println("Player is in start state");
context.setState(this);
}
public String toString(){
return "Start State";
}
}
public class StopState implements State {
public void doAction(Context context) {
System.out.println("Player is in stop state");
context.setState(this);
}
public String toString(){
return "Stop State";
}
}
public class Context {
private State state;
public Context(){
state = null;
}
public void setState(State state){
this.state = state;
}
public State getState(){
return state;
}
}
public class StatePatternDemo {
public static void main(String[] args) {
Context context = new Context();
StartState startState = new StartState();
startState.doAction(context);
System.out.println(context.getState().toString());
StopState stopState = new StopState();
stopState.doAction(context);
System.out.println(context.getState().toString());
}
}