zoukankan      html  css  js  c++  java
  • 3.js模式-策略模式

    1. 策略模式

    策略模式定义一系列的算法,把它们封装起来,并且可以互相替换。

    var strategies = {

          isNonEmpty: function(value,errMsg){

                 if(value === ''){

                        return errMsg;

                 }

          },

          minLength:function(value,length,errMsg){

                 if(value.length < length){

                        return errMsg;

                 }

          }

    }

    var validator = function(){

          this.cache = [];

    }

    validator.prototype.add = function(dom,rule,errMsg){

          var array = rule.split(':');

          this.cache.push(function(){

                 var strategy = array.shift();

                 array.unshift(dom.value);

                 array.push(errMsg);

                 return strategies[strategy].apply(dom, array);

          });

    }

    validator.prototype.validate = function(){

          for(var i =0,validatorFunc;validatorFunc=this.cache[i++];){

                 var msg = validatorFunc();

                 if(msg){

                        return msg;

                 }

          }

    }

    validator.add(form.name,'isNonEmpty','用户名不能为空');

    validator.add(form.name,'minLength:10','用户名不能为空');

    validator.validate();

  • 相关阅读:
    CodeForces 446A. DZY Loves Sequences(最长上升子序列)
    CodeForces
    2020牛客暑期多校训练营(第一场)
    POJ3281-Dining(最大流)(拆点)
    「杂题」图论杂题选做
    「学习小结」CDQ 分治多维偏序问题
    「算法笔记」Tarjan 算法 双连通分量
    「算法笔记」状压 DP
    「算法笔记」数位 DP
    「算法笔记」矩阵乘法
  • 原文地址:https://www.cnblogs.com/SLchuck/p/4869711.html
Copyright © 2011-2022 走看看