策略模式定义:定义一系列的算法,把它们一个个封装起来,并且使它们可以互相替换。
用策略模式实现表单验证:
var rules = {
isNonEmpty: function(value, errorMsg) {
if (value === '') {
return errorMsg;
}
},
minLength: function(value, length, errorMsg) {
if (value.length < length) {
return errorMsg;
}
}
};
var Validator = function() {
this.cache = [];
}
Validator.prototype.add = function (dom, rule, errorMsg) {
var ary = rule.split(':');
this.cache.push(function() {
var strategy = ary.shift();
ary.unshift(dom);
ary.push(errorMsg);
return rules[strategy].apply(dom, ary);
});
}
Validator.prototype.start = function() {
for (var i = 0, validatorFunc; validatorFunc = this.cache[i++];) {
var msg = validatorFunc();
if (msg) {
return msg;
}
}
}
var validatorFunc = function() {
var validator = new Validator();
validator.add(registerForm.username.value, 'isNonEmpty', '用户名不能为空!');
validator.add(registerForm.password.value, 'minLength:10', '密码不能少于10位!');
var errorMsg = validator.start();
return errorMsg;
}
var registerForm = document.getElementById('form');
registerForm.onsubmit = function() {
var errorMsg = validatorFunc();
if (errorMsg) {
alert(errorMsg);
return false;
}
}
使用策略模式让表单验证易于切换、易于理解、易于扩展。