Last active
May 22, 2020 04:29
-
-
Save drenther/5dc1fd31ce1b68e15dfcc1c6031094ca to your computer and use it in GitHub Desktop.
Behavioural Pattern - State
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TrafficLight { | |
constructor() { | |
this.states = [new GreenLight(), new RedLight(), new YellowLight()]; | |
this.current = this.states[0]; | |
} | |
change() { | |
const totalStates = this.states.length; | |
let currentIndex = this.states.findIndex(light => light === this.current); | |
if (currentIndex + 1 < totalStates) this.current = this.states[currentIndex + 1]; | |
else this.current = this.states[0]; | |
} | |
sign() { | |
return this.current.sign(); | |
} | |
} | |
class Light { | |
constructor(light) { | |
this.light = light; | |
} | |
} | |
class RedLight extends Light { | |
constructor() { | |
super('red'); | |
} | |
sign() { | |
return 'STOP'; | |
} | |
} | |
class YellowLight extends Light { | |
constructor() { | |
super('yellow'); | |
} | |
sign() { | |
return 'STEADY'; | |
} | |
} | |
class GreenLight extends Light { | |
constructor() { | |
super('green'); | |
} | |
sign() { | |
return 'GO'; | |
} | |
} | |
// usage | |
const trafficLight = new TrafficLight(); | |
console.log(trafficLight.sign()); // 'GO' | |
trafficLight.change(); | |
console.log(trafficLight.sign()); // 'STOP' | |
trafficLight.change(); | |
console.log(trafficLight.sign()); // 'STEADY' | |
trafficLight.change(); | |
console.log(trafficLight.sign()); // 'GO' | |
trafficLight.change(); | |
console.log(trafficLight.sign()); // 'STOP' |
Haha! No one noticed this including me for so long. Thanks for pointing it out, Will fix it soon!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good example of the state pattern and well coded. BTW, a traffic light goes GREEN->YELLOW->RED. Yours goes GREEN->RED->YELLOW; drivers will have to slam on their brakes when going to RED and will get a warning when they can gun it on GREEN.