2015-09-07 11:44:36 -06:00
|
|
|
// patterns/state/StateMachineDemo.java
|
2016-12-30 17:23:13 -08:00
|
|
|
// (c)2017 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// The StateMachine pattern and Template method
|
2016-07-28 12:48:23 -06:00
|
|
|
// {java patterns.state.StateMachineDemo}
|
2015-06-15 17:47:35 -07:00
|
|
|
package patterns.state;
|
2016-12-21 11:06:49 -08:00
|
|
|
import onjava.Nap;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
interface State {
|
|
|
|
void run();
|
|
|
|
}
|
|
|
|
|
|
|
|
abstract class StateMachine {
|
|
|
|
protected State currentState;
|
2016-11-21 12:37:57 -08:00
|
|
|
protected abstract boolean changeState();
|
2015-06-15 17:47:35 -07:00
|
|
|
// Template method:
|
|
|
|
protected final void runAll() {
|
|
|
|
while(changeState()) // Customizable
|
|
|
|
currentState.run();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// A different subclass for each state:
|
|
|
|
|
|
|
|
class Wash implements State {
|
|
|
|
@Override
|
|
|
|
public void run() {
|
|
|
|
System.out.println("Washing");
|
2017-01-22 16:48:11 -08:00
|
|
|
new Nap(0.5);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Spin implements State {
|
|
|
|
@Override
|
|
|
|
public void run() {
|
|
|
|
System.out.println("Spinning");
|
2017-01-22 16:48:11 -08:00
|
|
|
new Nap(0.5);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Rinse implements State {
|
|
|
|
@Override
|
|
|
|
public void run() {
|
|
|
|
System.out.println("Rinsing");
|
2017-01-22 16:48:11 -08:00
|
|
|
new Nap(0.5);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Washer extends StateMachine {
|
|
|
|
private int i = 0;
|
|
|
|
// The state table:
|
2016-11-21 12:37:57 -08:00
|
|
|
private State[] states = {
|
2015-06-15 17:47:35 -07:00
|
|
|
new Wash(), new Spin(),
|
|
|
|
new Rinse(), new Spin(),
|
|
|
|
};
|
2017-05-01 14:33:10 -06:00
|
|
|
Washer() { runAll(); }
|
2015-06-15 17:47:35 -07:00
|
|
|
@Override
|
|
|
|
public boolean changeState() {
|
|
|
|
if(i < states.length) {
|
|
|
|
// Change the state by setting the
|
|
|
|
// surrogate reference to a new object:
|
|
|
|
currentState = states[i++];
|
|
|
|
return true;
|
|
|
|
} else
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class StateMachineDemo {
|
2016-01-25 18:05:55 -08:00
|
|
|
public static void main(String[] args) {
|
2015-06-15 17:47:35 -07:00
|
|
|
new Washer();
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
Washing
|
|
|
|
Spinning
|
|
|
|
Rinsing
|
|
|
|
Spinning
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|