Created
September 21, 2021 07:34
-
-
Save tdimnet/cf14c09dabb548605c0ab381bec7ebf9 to your computer and use it in GitHub Desktop.
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
// Le Context | |
class TrafficLight { | |
constructor() { | |
this._states = [ | |
new GreenLight(), | |
new YellowLight(), | |
new RedLight() | |
] | |
this._currentLight = this._states[0] | |
} | |
handleTraffic() { | |
const totalStates = this._states.length | |
const currentIndex = this._states.findIndex(light => light === this._currentLight) | |
if (currentIndex + 1 < totalStates) { | |
this._currentLight = this._states[currentIndex + 1] | |
} else { | |
this._currentLight = this._states[0] | |
} | |
} | |
sign() { | |
return this._currentLight.sign() | |
} | |
} | |
// Les States | |
class RedLight { | |
constructor() { | |
this._light = 'red' | |
} | |
sign() { | |
return "S'arreter" | |
} | |
} | |
class YellowLight { | |
constructor() { | |
this._light = 'yellow' | |
} | |
sign() { | |
return 'Ralentir' | |
} | |
} | |
class GreenLight { | |
constructor() { | |
this._light = 'green' | |
} | |
sign() { | |
return 'Démarrer' | |
} | |
} | |
const Context = new TrafficLight() | |
console.log(Context.sign()) | |
Context.handleTraffic() | |
console.log(Context.sign()) | |
Context.handleTraffic() | |
console.log(Context.sign()) | |
Context.handleTraffic() | |
console.log(Context.sign()) | |
Context.handleTraffic() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment