js:策略模式
2017-11-27 23:27
344 查看
策略模式
定义一系列算法,将各算法封装起来,并且可以互相替换。即一类函数封装好后,再由一个接口函数实现根据不同参数调用不同函数。
简单理解:
var testFuncs = { "A": function(a,b){ return parseInt(a) + parseInt(b);}, "B": function(a,b){ return parseInt(a) - parseInt(b);}, "C": function(a,b){ return parseInt(a) * parseInt(b);}, "D": function(a,b){ return parseInt(a) / parseInt(b);} } var testInterface = function(fname, a, b){ return testFuncs[fname](a,b); } console.log( testInterface("A", "1", "2a") ); console.log( testInterface("B", "1", "2A") ); console.log( testInterface("D", "1", "2D") );
应用于表单验证:
(function(win){ var Validator = function(){ // 保存规则 this.rules = {}; // 内部添加一些规则 // 必要性检查 this.addRule( function(arr){ if(arr[0] === "") return false; return true; }, "isRequire"); // 最小长度检查 this.addRule( function(arr){ if(arr[0].length < arr[1]) return false; return true; }, "minLength"); // 最大长度检查 this.addRule( function(arr){ if(arr[0].length > arr[1]) return false; return true; }, "maxLength"); // 手机号检查 this.addRule( function(arr){ if(!(/(^1[3|5|8][0-9]{9}$)/).test(arr[0]) ) return false; return true; }, "isPhoneNum"); } // 外部可 动态添加策略 Validator.prototype.addRule = function(fn, ruleName){ if (this.rules[ruleName]) return true; this.rules[ruleName] = fn; } /**业务调用 校验接口 * arr [ [ruleName, [rule参数1,rule参数2.], errMsg],... ] */ Validator.prototype.check = function(arr){ var tempRule = null , tempCheck = null; for (var i=0, len = arr.length; i<len; i++){ tempCheck = arr[i]; if (tempCheck.length < 3) throw new Error("要检查的项 " + i + ": 参数不足"); tempRule = this.rules[tempCheck[0]]; if (!tempRule) throw new Error("未定义校验规则:" + tempCheck[0]); // 检查 规则校验结果,第一次遇到不满足 便退出 if (!tempRule(tempCheck[1])){ return tempCheck[2]; } tempRule = null; } // 所有检查结束且满足规则,返回 true return true; } win.Validator = Validator; })(window); var validator = new Validator; var str1 = "sfdgdg"; var name1 = "Asddddd"; var phone1 = "1265554"; var res = validator.check([ ["isRequire", [str1], "str1 不能为空"] ]); // 不使用 != 检查 if (res !== true){ console.log(res); }else{ console.log("验证通过"); // 输出 验证通过 } res = validator.check([ ["isRequire", [str1], "str1 不能为空"] ,["minLength", [name1, 6], "name1 长度至少为6。"] ,["maxLength", [name1, 10], "name1 长度最大为10。"] ,["isPhoneNum", [phone1], "phone1 不是正确的手机号。"] ]); if (res !== true){ console.log(res); // 输出 phone1 不是正确的手机号 }else{ console.log("验证通过"); }
相关文章推荐
- JS 设计模式--策略模式
- 理解js设计模式之策略模式
- 大熊君说说JS与设计模式之------策略模式Strategy
- JS中策略模式变成--面向未来变成
- js设计模式--策略模式
- JS设计模式-策略模式
- 策略模式--js设计模式与开发实践-7
- JS常用的设计模式(9)——策略模式
- js策略模式
- 【JS设计模式】策略模式的代码示例
- 鄙人最近搞的JS验证类(采用策略模式,极易扩展)
- js-设计模式学习笔记-策略模式
- js 策略模式
- js策略模式
- JS设计模式之策略模式
- JS设计模式之策略模式概念与用法分析
- JS设计模式——策略模式
- js之策略模式
- JS设计模式-策略模式
- 鄙人最新作JS验证组件采用策略模式易扩展