-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstate.js
72 lines (59 loc) · 1.2 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
class CarStateStopped {
constructor(car) {
this._car = car
console.log('Car is stopped')
}
start() {
this._car._engineWorks = true
this._car._speed = 0
this._car._changeState(new CarStateStarted(this._car))
}
stop() {
throw new Error('Car is stopped already')
}
changeSpeed() {
throw new Error('Car is not driven')
}
}
class CarStateStarted {
constructor(car) {
this._car = car
console.log('Car is started')
}
start() {
throw new Error('Car is already started')
}
stop() {
this._car._speed = 0
this._car._engineWorks = false
this._car._changeState(new CarStateStopped(this._car))
}
changeSpeed(value) {
console.log(`Setting speed to ${value}`)
if (value >= 0) {
this._car._speed = value
} else {
throw new Error("Speed value can't be negative")
}
}
}
class Car {
constructor() {
this._speed = 0
this._engineWorks = false
this._state = new CarStateStopped(this)
}
start() {
this._state.start(this)
}
stop() {
this._state.stop(this)
}
changeSpeed(value) {
this._state.changeSpeed(value)
}
_changeState(newState) {
this._state = newState
}
}
module.exports = Car