State Design Pattern in Java: Case statement considered harmful
- Create a State class hierarchy
- The State base class has a single method
void pull(Chain wrapper)
The method can be abstract, or, it can contain default behavior - Create a State derived class for each condition in the if-then-else statement
- Move each
println()
statement to thepull()
method of its appropriate class - Make the Chain class a "wrapper" class that models the state machine abstraction
- The Chain class maintains a "current" State object
- All client requests [i.e.
pull()
] are simply delegated to the current state object and the wrapper object's "this" pointer is passed - The Chain class needs a constructor that initializes its current state
- It also needs a
setState()
method that the State derived classes can use to change the state of the state machine - Call the
setState()
method as necessary in each of the State derived classespull()
methods
class Chain {
private int state;
public Chain() {
state = 0;
}
public void pull() {
if (state == 0) {
state = 1;
System.out.println( " low speed" );
} else if (state == 1) {
state = 2;
System.out.println( " medium speed" );
} else if (state == 2) {
state = 3;
System.out.println( " high speed" );
} else {
state = 0;
System.out.println( " turning off" );
}
}
}
public class StateDemo {
public static void main( String[] args ) throws IOException {
InputStreamReader is = new InputStreamReader( System.in );
Chain chain = new Chain();
while (true) {
System.out.print( "Press 'Enter'" );
is.read();
chain.pull();
}
}
}
Output
Press 'Enter' low speed Press 'Enter' medium speed Press 'Enter' high speed Press 'Enter' turning off Press 'Enter' low speed Press 'Enter' medium speed Press 'Enter' high speed Press 'Enter' turning off