Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【JavaScript设计模式与开发实践】第十六章 - 状态模式 #59

Open
Kelichao opened this issue Jul 21, 2017 · 0 comments
Open

Comments

@Kelichao
Copy link
Owner

Kelichao commented Jul 21, 2017

状态模式

        var Light = function () {
            this.currState = FSM.off; // 设置当前状态
            this.button = null;
        };
        Light.prototype.init = function () {
            var button = document.createElement('button'),
                self = this;
            button.innerHTML = '已关灯';
            this.button = document.body.appendChild(button);

            
            this.button.onclick = function () {
                self.currState.buttonWasPressed.call(self); // 把请求委托给FSM 状态机
            }
        };

        // 状态机
        var FSM = {
            off: {
                buttonWasPressed: function () {
                    console.log('关灯');
                    this.button.innerHTML = '下一次按我是开灯';
                    this.currState = FSM.on;
                }
            },
            on: {
                buttonWasPressed: function () {
                    console.log('开灯');
                    this.button.innerHTML = '下一次按我是关灯';
                    this.currState = FSM.off;
                }
            }
        };
        var light = new Light();
        light.init();
@Kelichao Kelichao changed the title 【JavaScript设计模式与开发实践】第十六章 - 中介者模式 【JavaScript设计模式与开发实践】第十六章 - 状态模式 Aug 14, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant