Created
November 6, 2017 11:23
-
-
Save nitin42/4d643d7812bcc763351dfea59f5fb0ff to your computer and use it in GitHub Desktop.
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
| var TrafficLight = function () { | |
| var count = 0; | |
| var currentState = new Red(this); | |
| this.change = function (state) { | |
| // limits number of changes | |
| if (count++ >= 10) return; | |
| currentState = state; | |
| currentState.go(); | |
| }; | |
| this.start = function () { | |
| currentState.go(); | |
| }; | |
| } | |
| var Red = function (light) { | |
| this.light = light; | |
| this.go = function () { | |
| log.add("Red --> for 1 minute"); | |
| light.change(new Green(light)); | |
| } | |
| }; | |
| var Yellow = function (light) { | |
| this.light = light; | |
| this.go = function () { | |
| log.add("Yellow --> for 10 seconds"); | |
| light.change(new Red(light)); | |
| } | |
| }; | |
| var Green = function (light) { | |
| this.light = light; | |
| this.go = function () { | |
| log.add("Green --> for 1 minute"); | |
| light.change(new Yellow(light)); | |
| } | |
| }; | |
| // log helper | |
| var log = (function () { | |
| var log = ""; | |
| return { | |
| add: function (msg) { log += msg + "\n"; }, | |
| show: function () { alert(log); log = ""; } | |
| } | |
| })(); | |
| function run() { | |
| var light = new TrafficLight(); | |
| light.start(); | |
| log.show(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment