-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathState.js
95 lines (80 loc) · 2.12 KB
/
State.js
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
// class Light {
// constructor() {
// this.state = 'off'; //电灯默认为关闭状态
// this.button = null;
// }
// init() {
// let button = document.createElement('button');
// let self = this;
// button.innerHTML = '我是开关';
// this.button = document.body.appendChild(button);
// this.button.onclick = () => {
// self.buttonWasClicked();
// }
// }
// buttonWasClicked() {
// if (this.state === 'off') {
// console.log('开灯');
// this.state = 'on';
// } else {
// console.log('关灯');
// this.state = 'off';
// }
// }
// }
// let light = new Light();
// light.init();
// 定义三个不同的状态类
// 灯未开启的状态
class OffLightState {
constructor(light) {
this.light = light;
}
buttonWasClicked() {
console.log('切换到弱光模式');
this.light.setState(this.light.weakLightState);
}
}
// 弱光状态
class WeakLightState {
constructor(light) {
this.light = light;
}
buttonWasClicked() {
console.log('切换到强光模式');
this.light.setState(this.light.strongLightState);
}
}
// 强光状态
class StrongLightState {
constructor(light) {
this.light = light;
}
buttonWasClicked() {
console.log('关灯');
this.light.setState(this.light.offLightState);
}
}
class Light {
constructor() {
this.offLightState = new OffLightState(this);
this.weakLightState = new WeakLightState(this);
this.strongLightState = new StrongLightState(this);
this.button = null;
}
init() {
let button = document.createElement('button');
let self = this;
button.innerHTML = '我是开关';
this.button = document.body.appendChild(button);
this.curState = this.offLightState;
this.button.onclick = () => {
self.curState.buttonWasClicked();
}
}
setState(state) {
this.curState = state;
}
}
let light = new Light();
light.init();