SE450: State: An example [18/24] Previous pageContentsNext page

Remember the awful finite state machine from Homework 3?

file:Control.java [source] [doc-public] [doc-private]

Here is a version refactored to the state pattern:

file:Control.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package state.ui.main;

import state.ui.UI;
import state.ui.UIMenu;
import state.ui.UIMenuBuilder;

class Control {
  final State EXITED;
  final State EXIT;
  private State state;
  Control(UI ui) {
    EXITED = new ExitedState();
    EXIT = new ExitState(this,ui);
    state = EXIT;
  }

  void run() {
    while (state != EXITED) {
      state = state.run();
    }
  }
}

interface State {
  public State run();
}

final class ExitedState implements State {
  public State run() {
    return this;
  }
}

final class ExitState implements State {
  Control control;
  UI ui;
  UIMenu m;
  ExitState(Control control, UI ui) {
    this.control = control;
    this.ui = ui;

    UIMenuBuilder mb;
    mb = new UIMenuBuilder();

    //mb.add("Default", new UIMenuAction() { public Object run() {return this;} });
    mb.add("Default", () -> this);
    mb.add("Yes", () -> control.EXITED);
    mb.add("No", () -> control.EXIT);
    this.m = mb.toUIMenu("Are you sure you want to exit?");
  }
  public State run() {
    return (State) ui.processMenu(m);
  }
}

Full code: dir:state/ui [source]

Previous pageContentsNext page