-
Notifications
You must be signed in to change notification settings - Fork 1
/
ClassicStateImpl.java
72 lines (60 loc) · 1.31 KB
/
ClassicStateImpl.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
// State pattern: classic Gang of Four implementation - simulating light switch
package behavioral.state.classic;
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 or OffState
public LightSwitch()
{
state = new OffState();
}
public void setState(State state) {
this.state = state;
}
void on() { state.on(this); }
void off() { state.off(this); }
}
class ClassicStateDemo
{
public static void main(String[] args)
{
LightSwitch lightSwitch = new LightSwitch();
lightSwitch.on();
lightSwitch.off();
lightSwitch.off();
}
}