Skip to content

Instantly share code, notes, and snippets.

@drenther
Last active May 22, 2020 04:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drenther/5dc1fd31ce1b68e15dfcc1c6031094ca to your computer and use it in GitHub Desktop.
Save drenther/5dc1fd31ce1b68e15dfcc1c6031094ca to your computer and use it in GitHub Desktop.
Behavioural Pattern - State
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'
@dturvene
Copy link

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.

@drenther
Copy link
Author

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