OnJava8-Examples/patterns/state/StateMachineDemo.java

77 lines
1.5 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// patterns/state/StateMachineDemo.java
// (c)2021 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.
// The State Machine pattern.
2016-07-28 12:48:23 -06:00
// {java patterns.state.StateMachineDemo}
2015-06-15 17:47:35 -07:00
package patterns.state;
import java.util.*;
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;
protected abstract boolean changeState();
2015-06-15 17:47:35 -07:00
// Template method:
protected final void runAll() {
while(changeState())
2015-06-15 17:47:35 -07:00
currentState.run();
}
}
// A different subclass for each state:
class Wash implements State {
@Override public void run() {
2015-06-15 17:47:35 -07:00
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() {
2015-06-15 17:47:35 -07:00
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() {
2015-06-15 17:47:35 -07:00
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;
private Iterator<State> states =
Arrays.asList(
new Wash(), new Spin(),
new Rinse(), new Spin()
).iterator();
2017-05-01 14:33:10 -06:00
Washer() { runAll(); }
@Override public boolean changeState() {
if(!states.hasNext())
2015-06-15 17:47:35 -07:00
return false;
// Set the surrogate reference
// to a new State object:
currentState = states.next();
return true;
2015-06-15 17:47:35 -07:00
}
}
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
*/