-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStateDemo.java
72 lines (55 loc) · 1.24 KB
/
StateDemo.java
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
package state;
class State {
void on(LightSwitch ls) {
System.out.println("light is already on.");
}
void off(LightSwitch ls) {
System.out.println("light is already off.");
}
}
class OnState extends State {
public OnState() {
System.out.println("Light turned on");
}
@Override
void off(LightSwitch ls) {
System.out.println("switching light off...");
ls.setState(new OffState());
}
}
class OffState extends State {
public OffState() {
System.out.println("light turned off...");
}
@Override
void on(LightSwitch ls) {
System.out.println("switching light on...");
ls.setState(new OnState());
}
}
class LightSwitch {
private State state; //OnState, OffState
public LightSwitch() {
this.state = new OffState();
}
void on() {
state.on(this);
}
void off() {
state.off(this);
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
public class StateDemo {
public static void main(String[] args) {
LightSwitch ls = new LightSwitch();
ls.on();
ls.off();
ls.off();
}
}