javascript设计模式-策略模式

时间:2024-01-07 18:01:20

策略模式笔记
   将定义的一组算法封装起来,使其相互之间可以替换。
   封装的算法具有一定独立性,不会随客户端变化而变化。
   与状态模式异同?
     1. 结构上看,它与状态模式很像,也是在内部封装一个对象,然后通过返回的接口对象实现对内部对象的调用
     2. 不同点是,策略模式不需要管理状态,状态之间没有依赖关系、策略之间可以相互替换、策略对象内部保存的是相互独立的一些算法。
   demo:价格策略对象 、 表单正则验证策略对象

demo1:价格策略对象

             //价格策略对象
var PriceStrategy = function(){
//内部算法对象
var strategy = {
//100 返 30
return30 : function(price){
return +price + parseInt(price / 100) * 30;
},
//100 返 50
return50 : function(price){
return +price + parseInt(price / 100) * 50;
},
//9折
percent90 : function(price){
return price * 100 * 90 / 10000;
},
//8折
percent80 : function(price){
return price * 100 * 80 / 10000;
},
//5折
percent50 : function(price){
return price * 100 * 50 / 10000;
}
}
return function(algorithm,price){
//如果算法存在,则调用算法,否则返回false
return strategy[algorithm] && strategy[algorithm](price);
}
}();

测试代码

1             var price = PriceStrategy('return50','300');
console.log(price);

控制台显示

javascript设计模式-策略模式

demo2: 表单正则验证策略对象

             //表单正则验证策略对象
var InputStrategy = function(){
var strategy = {
//是否为空
notNull : function(value){
return /\s+/.test(value) ? '请输入内容' : '';
},
//是否是一个数字
number : function(value){
return /^[0-9]+(\.[0-9]+)?$/.test(value) ? '' : '请输入数字';
},
//是否是本地电话
phone : function(value){
return /^\d{3}\-\d{8}$|^\d{4}\-\d{7}$/.test(value) ? '' : '请输入正确的电话号码格式,如:010-12345678 或 0418-1234567';
}
}
return {
//验证接口 type算法 value 表单值
check : function(type, value){
//去除收尾空白符
value =value.replace(/^\s+|\s+$/g, '');
return strategy[type] ? strategy[type](value) : '没有该类型的检测方法'
},
//添加策略
addStrategy : function(type, fn){
strategy[type] = fn;
}
}
}();

拓展策略 添加策略

          InputStrategy.addStrategy('nickname', function(value){
return /^[a-zA-Z]\w{3-7}$/.test(value) ? '' : '请输入4-8位昵称,如:YYQH';
});

测试代码

          console.log(InputStrategy.check('nickname',"1YQH"));

控制台显示

javascript设计模式-策略模式