Created
July 6, 2022 20:49
-
-
Save wolivera/57043d48d9b384a57cf1e52f92a16939 to your computer and use it in GitHub Desktop.
GoF 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.count = 0; | |
this.currentState = new Red(this); | |
} | |
change (state) { | |
// limits number of changes | |
if (this.count++ >= 10) return; | |
this.currentState = state; | |
this.currentState.go(); | |
} | |
start () { | |
this.currentState.go(); | |
} | |
} | |
class Red { | |
constructor(light) { | |
this.light = light; | |
} | |
go () { | |
console.log("Red --> for 1 minute"); | |
this.light.change(new Green(this.light)); | |
} | |
} | |
class Yellow { | |
constructor(light) { | |
this.light = light; | |
} | |
go () { | |
console.log("Yellow --> for 10 seconds"); | |
this.light.change(new Red(this.light)); | |
} | |
} | |
class Green { | |
constructor(light) { | |
this.light = light; | |
} | |
go () { | |
console.log("Green --> for 1 minute"); | |
this.light.change(new Yellow(this.light)); | |
} | |
} | |
const trafficLight = new TrafficLight(); | |
trafficLight.start(); | |
// Red --> for 1 minute | |
// Green --> for 1 minute | |
// Yellow --> for 10 seconds | |
// Red --> for 1 minute | |
// Green --> for 1 minute | |
// Yellow --> for 10 seconds | |
// Red --> for 1 minute | |
// Green --> for 1 minute | |
// Yellow --> for 10 seconds | |
// Red --> for 1 minute | |
// Green --> for 1 minute |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment