【设计模式】Javascript设计模式——状态模式(行为型)

注:这个模式是非常聪明的,很有点数学中组合的意思,现在,来看下这个模式是怎么个思想。

问题提出:假如某个操作有三种可能,分别为1,2,3,还可能是组合,比如先执行1,再执行2或者先执行2再执行3或者1,2,3等等,用常规的判定,代码如下:

        if (result == 1) {
            //执行方法
        }
        else if (result == 2) {
            //执行方法
        }
        else if (result == 3) {
            //执行方法
        }
        //....

现在只有3个结果的组合,如果是10个呢,这个判断条件就会无比复杂!

状态模式就是解决这种问题,它的思路比较巧妙,其思路是:把每种可能的结果都对应出来,如果出现某个可能就将其置为true,然后再扫描各个标志位,接着执行方法,一张图一目了然。

##示例代码:

        var ResultState = function () {
            var _currentState = {}; //状态

            var States = {          //状态和状态对应的方法
                1: function () {
                    console.log('执行1');
                },
                2: function () {
                    console.log('执行2');
                },
                3: function () {
                    console.log('执行3');
                }
            };
            /**************行为****************/
            var Action = {
                
                changeStae: function () {   /******改变状态******/
                    var arg = arguments;
                    _currentState = {};
                    if (arg.length) {
                        for (var i = 0; i < arg.length; i++) {
                            _currentState[arg[i]] = true;//选中
                        }
                    }
                    return this;
                },
                fire: function () {         /******执行方法******/
                    for (var i in _currentState) {
                        States[i] && States[i]();
                    }
                    return this;
                }
            };
            return {
                change: Action.changeStae,
                fire: Action.fire
            }
        };

        var o = ResultState();
        o.change(2, 3).fire().change(1, 3).fire().change(1, 2, 3).fire();
原文地址:https://www.cnblogs.com/tinaluo/p/8685258.html