SE450: State: Refactored to state using parameter and single instances [24/24] Previous pageContents

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
package state.three;

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

class C implements I {
  private CState state = CState.MINUS;
  int i;
  int j;
  public int f() {
    return state.f(this);
  }
  public int g() {
    return state.g(this);
  }
  public void changeDirection() {
    state = (state==CState.MINUS) ? CState.PLUS : CState.MINUS;
  }
}

file:CState.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
package state.three;

interface CState {
  public int f(C x);
  public int g(C x);

  public static final CState MINUS = new CStateMinus();
  public static final CState PLUS = new CStatePlus();
}

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

Previous pageContents