Skip to content

Instantly share code, notes, and snippets.

@israeleriston
Created April 26, 2018 01:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save israeleriston/6937067b97ba66fd8fd6b45dbac945e9 to your computer and use it in GitHub Desktop.
Save israeleriston/6937067b97ba66fd8fd6b45dbac945e9 to your computer and use it in GitHub Desktop.
Example of pattern State Manager
class Car {
constructor(count, currentState) {
this.count = 0
this.currentState = new Red(this)
}
change (state) {
if (this.count++ >= 10) {
return
}
this.currentState = state
this.currentState.go()
}
start () {
this.currentState.go()
}
}
class Red {
constructor(state) {
this.state = state
}
go () {
console.log('Red -> for 1 minute')
this.state.change(new Green(this.state))
}
}
class Green {
constructor(state) {
this.state = state
}
go () {
console.log('Green -> for 1 minute')
this.state.change(new Yellow(this.state))
}
}
class Yellow {
constructor(state) {
this.state = state
}
go () {
console.log('Yellow -> for 10 minute')
this.state.change(new Red(this.state))
}
}
const run = () => {
const car = new Car()
car.start()
}
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment