Created
April 1, 2019 19:10
-
-
Save m1nd/a8ccb8d53ec7b1323eead2559adb8c44 to your computer and use it in GitHub Desktop.
State pattern
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 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"); | |
| light.change(new Green(light)); | |
| } | |
| } | |
| class Yellow { | |
| constructor(light) { | |
| this.light = light | |
| } | |
| go = () => { | |
| console.log("Yellow --> for 10 seconds"); | |
| light.change(new Red(light)); | |
| } | |
| } | |
| class Green { | |
| constructor(light) { | |
| this.light = light | |
| } | |
| go = () => { | |
| console.log("Green --> for 1 minute"); | |
| light.change(new Yellow(light)); | |
| } | |
| } | |
| const light = new TrafficLight(); | |
| light.start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment