Heim  >  Artikel  >  Web-Frontend  >  Überprüfen Sie die Implementierung des Strategiemusters

Überprüfen Sie die Implementierung des Strategiemusters

一个新手
一个新手Original
2017-09-22 09:47:341245Durchsuche


// 定义策略var strategy = {
    isNotEmpty: function(value, errorMsg){
        if(value === ''){            
        return errorMsg;
        }
    },
    minLength: function(value, length, errorMsg){
        if(value.length < length){            
        return errorMsg;
        }
    },
    mobileFormat: function(value, errorMsg){
        if(!/(^1[3|5|8][0-9]{9}$)/.test(value)){            
        return errorMsg;
        }
    }
}function Validator() {
    this.cache = [];
}
Validator.prototype.add = function(value, rules){
    for(var i = 0, rule; rule = rules[i++];){        
    var self = this;
        (function(rule){
            self.cache.push(function(){
                var strategyRule = rule.strategy.split(&#39;:&#39;);                
                var strategyName = strategyRule.shift();                // 各位看官注意啦, 如果直接使用[value].concat(strategyRule.push(rule.errorMsg))会出问题
                // 什么问题呢? 
                // strategyRule.push(rule.errorMsg)这货会返回length, 我TM调试了半天!
                strategyRule.push(rule.errorMsg);                
                var arr = [value].concat(strategyRule);                
                return strategy[strategyName].apply(null,arr);
            })
        })(rule);
    }
}
Validator.prototype.check = function(){
    for(var i = 0, checkFn; checkFn = this.cache[i++];){        
    var msg = checkFn();        
    if(msg){            
    return msg;
        }
    }
}var validator = new Validator();
validator.add(&#39;12345&#39;, [
    {
        strategy: &#39;isNotEmpty&#39;,
        errorMsg: &#39;in not empty&#39;
    },
    {
        strategy: &#39;minLength:10&#39;,
        errorMsg: &#39;length is less than 10&#39;
    }
]);var tip = validator.check(); // tip: length is less than 10

Das obige ist der detaillierte Inhalt vonÜberprüfen Sie die Implementierung des Strategiemusters. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn