策略模式

来源:互联网 发布:手机淘宝降价提醒 编辑:程序博客网 时间:2024/06/16 14:53

定义

定义一系列的算法,把他们一个个封装起来,并使他们可以相互替换。策略模式利用组合,多态的思想有效避免了多重条件分支,提供了open-close原则的完美支持。使用策略模式必须了解所有的strategy。

使用策略模式计算奖金

将计算方法封装起来,避免使用条件分支判断
        var strategies = {            "S": function(salary){                return salary * 4;            },            "A":function(salary){                return salary * 3;            },            "B":function(salary){                return salary * 2            }        }        var calculateBonus = function(level,salary){            return strategies[level](salary)        }        console.log(calculateBonus('S',2000))

使用策略模式编写动画

        var tween = {            linear:function(t,b,c,d){                return c*t/d+b            },            easeIn:function(t,b,c,d){                return c*(t/=d)*t+b            }        }        var Animate = function(dom){            this.dom = dom;            this.startTime  = 0;            this.startPos = 0;            this.endPost = 0;            this.propertyName = null;//dom节点需要改变的属性名            this.easing = null;//缓动算法            this.duration = null;        }        Animate.prototype.start = function(propertyName,endPos,duration,easing){            this.startTime = +new Date;            this.startPos = this.dom.getBoundingClientRect()[propertyName]//dom节点初始位置            this.propertyName = propertyName;            this.endPos = endPos;            this.duration = duration;            this.easing = tween[easing];            var self = this;            var timeId = setInterval(function(){                if( self.step() == false ){                    clearInterval(timeId)                }            },19)        }        Animate.prototype.step = function(){            var  t = +new Date;            if( t >= this.startTime+this.duration){                this.update( this.endPos );                return false;            }            var pos = this.easing( t-this.startTime,this.startPos,                this.endPos-this.startPos,this.duration            )            this.update(pos);        }        Animate.prototype.update = function( pos ){            this.dom.style[this.propertyName] = pos + 'px';        }        var div = document.getElementById('na')        var animate = new Animate(div)        animate.start('left',500,1000,'linear')

表单验证

1. 策略对象维护验证方法2. Validator类添加验证规则3. 用户输入验证失败信息
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title></head><body>    <form action="http:/www.bai.com" id="registerForm" method='post'>        请输入用户名:<input type="text" name="userName">        请输入密码:<input type="text" name="password">        请输入手机号码:<input type="text" name="phoneNumber">        <button>提交</button>    </form>    <script>        /****策略对象*****/        var strategies = {            isNonEmpty:function(value,errorMsg){                if(value === ""){                    return errorMsg;                }            },            minLength:function(value,length,errorMsg){                if(value.length < length){                    return errorMsg                }            },            isMobile:function(value,errorMsg){                if( !/(^1[3|5|8][0-9]{9}$)/.test(value) ){                    return errorMsg                }            }        }        /****Validator类*****/        var Validator = function(){            this.cache = []        }        Validator.prototype.add = function( dom, rules ){            var self = this;            for(var i=0, rule; rule = rules[i++];){                (function(rule){                    var strategyAry = rule.strategy.split(':');                    var errorMsg = rule.errorMsg;                    //缓存用户传入所有验证要求                    self.cache.push(function(){                        var strategy = strategyAry.shift();                        strategyAry.unshift( dom.value );                        strategyAry.push( errorMsg );                        return strategies[strategy].apply( dom,strategyAry)                    })                })(rule)            }        }        //遍历缓存的函数,验证用户规则        Validator.prototype.start = function(){            for(var i=0, validatorFunc; validatorFunc = this.cache[i++];){                var errorMsg = validatorFunc();                if(errorMsg){                    return errorMsg                }            }        }        /*****客户调用代码****/        var registerForm = document.getElementById('registerForm');        var validataFunc = function(){            var validator = new Validator;            validator.add(registerForm.userName,[                {                    strategy:'isNonEmpty',                    errorMsg:'用户名不能为空'                },{                    strategy:'minLength:10',                    errorMsg:'用户名长度不能小于10位'                }            ])            validator.add(registerForm.password,[            {                    strategy:'minLength:6',                    errorMsg:'用户名密码长度不能小于6位'                }            ])            validator.add(registerForm.phoneNumber,[            {                    strategy:'isMobile',                    errorMsg:'手机号码格式不正确'                }            ])            var errorMsg = validator.start()            return errorMsg;         }        registerForm.onsubmit = function(){           var errorMsg = validataFunc();           if(errorMsg){               alert(errorMsg);               return false;           }       }    </script></body></html>
原创粉丝点击