|
| 1 | +// concurrent/Pizza.java |
| 2 | +// (c)2016 MindView LLC: see Copyright.txt |
| 3 | +// We make no guarantees that this code is fit for any purpose. |
| 4 | +// Visit http://OnJava8.com for more book information. |
| 5 | +import static java.util.concurrent.TimeUnit.*; |
| 6 | + |
| 7 | +public class Pizza { |
| 8 | + public enum Step { |
| 9 | + DOUGH(4), ROLLED(1), SAUCED(1), CHEESED(2), |
| 10 | + TOPPED(5), BAKED(2), SLICED(1), BOXED(0); |
| 11 | + int effort; // Needed to get to the next step |
| 12 | + Step(int effort) { this.effort = effort; } |
| 13 | + Step forward() { |
| 14 | + if(equals(BOXED)) return BOXED; |
| 15 | + try { |
| 16 | + MILLISECONDS.sleep(effort * 100); |
| 17 | + } catch(InterruptedException e) { |
| 18 | + throw new RuntimeException(e); |
| 19 | + } |
| 20 | + return values()[ordinal() + 1]; |
| 21 | + } |
| 22 | + } |
| 23 | + private Step step = Step.DOUGH; |
| 24 | + private final int id; |
| 25 | + public Pizza(int id) { this.id = id; } |
| 26 | + public void next() { |
| 27 | + step = step.forward(); |
| 28 | + System.out.println("Pizza " + id + ": " + step); |
| 29 | + } |
| 30 | + public void next(Step previousStep) { |
| 31 | + if(!step.equals(previousStep)) |
| 32 | + throw new IllegalStateException("Expected " + |
| 33 | + previousStep + " but found " + step); |
| 34 | + next(); |
| 35 | + } |
| 36 | + public void roll() { next(Step.DOUGH); } |
| 37 | + public void sauce() { next(Step.ROLLED); } |
| 38 | + public void cheese() { next(Step.SAUCED); } |
| 39 | + public void toppings() { next(Step.CHEESED); } |
| 40 | + public void bake() { next(Step.TOPPED); } |
| 41 | + public void slice() { next(Step.BAKED); } |
| 42 | + public void box() { next(Step.SLICED); } |
| 43 | + public boolean complete() { |
| 44 | + return step.equals(Step.BOXED); |
| 45 | + } |
| 46 | +} |
0 commit comments