SE450: State: Refactored to state using explicit field [22/24] Previous pageContentsNext page

file:I.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
56
57
58
59
package state.four;

interface I {
  public int f();
  public int g();
  public void changeDirection();
}

class C implements I {
  private CState state = new CStateMinus(this);
  int i;
  int j;
  public int f() {
    return state.f();
  }
  public int g() {
    return state.g();
  }
  public void changeDirection() {
    state = state.next();
  }
}

interface CState {
  public int f();
  public int g();
  public CState next();
}
class CStateMinus implements CState {
  C x;
  CStateMinus(C x) { this.x = x; }
  public int f() {
    x.i -= 32;
    return x.i;
  }
  public int g() {
    x.j -= 27;
    return x.j;
  }
  public CState next() {
    return new CStatePlus(x);
  }
}
class CStatePlus implements CState {
  C x;
  CStatePlus(C x) { this.x = x; }
  public int f() {
    x.i += 26;
    return x.i;
  }
  public int g() {
    x.j += 42;
    return x.j;
  }
  public CState next() {
    return new CStateMinus(x);
  }
}

Previous pageContentsNext page