策略模式
策略模式支持运行时选择算法,客户端只需要一个接口,可以根据不同的数据和业务需求,接口内部会选择不同的算法去适应。
validator = {
types:{},
messages:[],
config:{},
validate:function (data) {
var I,type,msg,checker,result_ok;
for(I in data){
if(data.hasOwnProperty(i)){
type = this.config[I];
checker = this.types[type];
if(!type){
continue;
}
if(!checker){
throw{
name:'ValidationError',
message:'No handler to validate type' + type;
}
}
result_ok = checker.validate(data[I]);
if(!result_ok){
msg = 'Invalid value for *' + I + '*,' + checker.instructions;
this.messages.push(msg);
}
}
}
return this.hasErrors();
},
hasErrors: function () {
return this.messages.length !== 0;
}
};
Validator.config = {
first_name:'isNotEmpty'
};
Validator.types.isNotEmpty = {
validate:function (data) {
return data !== '';
},
instructions:'the value cannot be empty';
};