SE450: Template Method: Template Example [32/35] Previous pageContentsNext page

file:Main.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
55
package template.ftoc;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

/* This example is from Robert C. Martin */
public class Main {
  public static void main(String[] args) {
    (new FtoC()).run();
  }
}
/* public */
abstract class Application {
  private boolean isDone = false;

  protected abstract void init();
  protected abstract void idle();
  protected abstract void cleanup();
  protected boolean done() {
    return isDone;
  }
  protected void setDone() {
    isDone = true;
  }
  public void run() {
    init();
    while (!done())
      idle();
    cleanup();
  }
}
final class FtoC extends Application {
  private BufferedReader br;

  protected void init() {
    br = new BufferedReader(new InputStreamReader(System.in));
  }
  protected void idle() {
    String fstring = readLine();
    if (fstring == null || fstring.length() == 0) {
      setDone();
    } else {
      double f = Double.parseDouble(fstring);
      double c = 5.0/9.0*(f-32);
      System.out.println("F=" + f + ", C=" + c);
    }
  }
  protected void cleanup() {
    System.out.println("FtoC exit");
  }
  private String readLine() {
    try { return br.readLine(); }
    catch(IOException e) { return null; }
  }
}

Previous pageContentsNext page