Created
April 26, 2018 01:00
-
-
Save israeleriston/6937067b97ba66fd8fd6b45dbac945e9 to your computer and use it in GitHub Desktop.
Example of pattern State Manager
This file contains hidden or 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 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