-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathState.java
More file actions
97 lines (78 loc) · 2.33 KB
/
State.java
File metadata and controls
97 lines (78 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import static org.junit.Assert.assertEquals;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
interface State {
State enterDigit(int i);
String getStatus();
}
class LockedState implements State {
private int[] combination;
private int currentIndex = 0;
LockedState(int[] combination) {
this.combination = combination;
this.currentIndex = 0;
}
public State enterDigit(int digit) {
if (digit == combination[currentIndex]) {
if (currentIndex == combination.length - 1) {
return new UnlockedState();
} else {
currentIndex++;
return this;
}
}
return new ErrorState();
}
public String getStatus() {
if (currentIndex == 0) {
return "LOCKED";
}
return IntStream.range(0, currentIndex).mapToObj(i -> "" + combination[i]).collect(Collectors.joining());
}
}
class UnlockedState implements State {
public State enterDigit(int i) {
return new ErrorState();
}
public String getStatus() {
return "OPEN";
}
}
class ErrorState implements State {
public State enterDigit(int i) {
return this;
}
public String getStatus() {
return "ERROR";
}
}
class CombinationLock {
int[] combination;
public String status;
State state;
public CombinationLock(int[] combination) {
this.combination = combination;
this.state = combination.length == 0 ? new UnlockedState() : new LockedState(combination);
status = state.getStatus();
}
public void enterDigit(int digit) {
state = state.enterDigit(digit);
status = state.getStatus();
}
}
class DemoState {
public static void main(String[] args) {
CombinationLock cl = new CombinationLock(new int[] { 1, 2, 3, 4 });
assertEquals("LOCKED", cl.status);
cl.enterDigit(1);
assertEquals("1", cl.status);
cl.enterDigit(2);
assertEquals("12", cl.status);
cl.enterDigit(3);
assertEquals("123", cl.status);
cl.enterDigit(4);
assertEquals("OPEN", cl.status);
cl.enterDigit(0);
assertEquals("ERROR", cl.status);
}
}