策列模式将一组算法封装起来使其相互之间可以替换。封装的算法具有独立性,不会随客户端变化而变化。
// //价格策列对象
// let PriceState = function () {
// //内部双算法对象
// let stragtegy = {
// //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) {
// //js 在处理乘法除有bug
// return price*100*90/10000;
// },
// //打八折
// percent80:function (price) {
// return price*100*90/10000;
// },
// //5折
// percent50:function (price) {
// return price*100*50/10000;
// }
// }
// return function (algo,price) {//构造函数
// return stragtegy[algo]&&stragtegy[algo](price);
// }
// }();
// let p = PriceState('return30',314.67);
// console.log(p);
let InputStrategy = function () {
let strateg = {
notNull:function (value) {
return value+" 不能为空";
}
}
return {
check:function (type,value) {
return strateg[type]?strateg[type](value):"该检测方法不存在";
},
addStrate:function (type,fn) {
strateg[type] = fn;
}
}
}();
let str = InputStrategy.check('notNull',"hello");
console.log(str);
InputStrategy.addStrate('say',function (value) {
return value + "说话";
});
let man = InputStrategy.check('say',"world");
console.log(man);