第5章策略模式

2017-10-09  本文已影响0人  入秋未凉的海

第5章策略模式

5.1 使用策略模式计算奖金

1最初的代码实现

var calculateBonus = function(performanceLevel,salary){
    if(performanceLevel === 's'){
        return salary*4;
    }
    if(performanceLevel === 'A'){
        return salary*3;
    }
    if(performanceLevel === 'B'){
        return salary*2;
    }
}

calculateBonus('B',20000);//40000
calculateBonus('S',6000);//24000

calculateBonus函数庞大

calculateBonus函数缺乏弹性 违反开放-封闭原则

算法复用性差

2使用组合函数重构代码

var perfoemanceS = function(salary){
    return salary*4;
0};
var perfoemanceA = function(salary){
    return salary*3;
0};
var perfoemanceB = function(salary){
    return salary*2;
0};

var calculeateBonus = function(performanceLevel,salary){
    if (performanceLevel === 'S') {
        return perfoemanceS(salary);
    }
    if (performanceLevel === 'A') {
        return perfoemanceA(salary);
    }
    if (performanceLevel === 'B') {
        return perfoemanceB(salary);
    }
}

calculeateBonus('A',10000)   //30000

3使用策略模式重构代码

var perfoemanceS = function(){}
perfoemanceS.prototype.calculate = function(salary){
    return salary*4;
}

var perfoemanceA = function(){};
perfoemanceA.prototype.calculate = function(salary){
    return salary*3;
}

var perfoemanceB = function(){}
perfoemanceB.prototype = function(salary){
    return salary*2;
}

var Bonus = function(){
    this.salary = null;
    this.strategy = null;
}

Bonus.prototype.satSalary = function(salary){
    this.salary = salary;
}
Bonus.prototype.satStrategy = function(strategy){
    this.strategy = strategy;
}
Bonus.prototype.getBonus = function(){
    return this.strategy.calculate(this.salary);
}

var bonus = new Bonus();
bonus.satSalary(10000);
bonus.satStrategy(new perfoemanceS);
console.log(bonus.getBonus()); //40000
bonus.satStrategy(new perfoemanceA())
console.log(bonus.getBonus()); //30000

5.2 Javascript版本的策略模式

var strategies = {
    "S":function(salary){
        return salary*4;
    },
    "A":function(salary){
        return salary*4;
    },
    "b":function(salary){
        return salary*2;
    }
}

var calculateBonus = function(level,salary){
    return strategies[level](salary);
}
console.log(calculateBonus('S',20000));
console.log(calculateBonus('A',10000))

5.3 多态在策略模式中的体现

当我们对这些策略对象发出“计算奖金”的请求时,它们会返回各自不同的计算结果,这正是对象多态性的体现。

5.4 使用策略模式实现缓动动画

5.4.1 实现动画效果原理

通过连续改变元素的某个CSS属性,比如left top background-position来实现动画效果。

5.4.2 思想和一些准备工作

5.4.3 让小球运动起来

缓动算法

var tween = {
    linear:function(t,b,c,d){
        return c*t/d+b;
    },
    easeIn:function(t,b,c,d){
        return c*(t/=d)*t+b;
    },
    strongEaseIn:function(t,b,c,d){
        return c*(t/=d)*t*t*t*t+b;
    },
    strongEaseOut:function(t,b,c,d){
        return c*((t=t/d - 1)*t*t*t*t+1)+b;
    },
    sineaseIn:function(t,b,c,d){
        return c*(t/=d)*t*t+b;
    },
    sineaseOut:function(t,b,c,d){
        return c*((t = t/d - 1)*t*t+1)+b
    }
}



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<div id="div" style="position: absolute;background: blue">我是div</div>

</body>
<script>
var tween = {
    linear:function(t,b,c,d){
        return c*t/d+b;
    },
    easeIn:function(t,b,c,d){
        return c*(t/=d)*t+b;
    },
    strongEaseIn:function(t,b,c,d){
        return c*(t/=d)*t*t*t*t+b;
    },
    strongEaseOut:function(t,b,c,d){
        return c*((t=t/d - 1)*t*t*t*t+1)+b;
    },
    sineaseIn:function(t,b,c,d){
        return c*(t/=d)*t*t+b;
    },
    sineaseOut:function(t,b,c,d){
        return c*((t = t/d - 1)*t*t+1)+b
    }
}
var Animate = function(dom){
    this.dom = dom; //dom节点
    this.startTime = 0;//开始时间
    this.startPos = 0;//dom节点开始位置
    this.endPos = 0;//dom结点结束位置
    this.propertyName = null;//dom节点需要被改变的css属性名
    this.easing = null;//缓动算法
    this.duration = null;//动画持续时间
}
Animate.prototype.start = function(propertyName,endPos,duration,easing){
    this.startTime = +new Date;
    this.startPos = this.dom.getBoundingClientRect()[propertyName];
    this.propertyName = propertyName;
    this.endPos = endPos;
    this.duration = duration;
    this.easing = tween[easing];   


    var self = this;
    var timeId = setInterval(function(){
        if(self.step()===false){
            clearInterval(timeId);

        }
    },19);
}
Animate.prototype.step = function(){
    var t = +new Date;
    if(t>=this.startTime+this.duration){
        this.update(this.endPos);
        return false;
    }
    var pos = this.easing(t-this.startTime,this.startPos,this.endPos-this.startPos,this.duration);
    this.update(pos);
}
Animate.prototype.update = function(pos){
    this.dom.style[this.propertyName] = pos + 'px'
}
var div = document.getElementById('div');
var animate = new Animate(div);
animate.start('left',500,1000,'strongEaseOut')
</script>
</html>

使用策略模式把算法传人动画类中,来达到各种不同的缓动效果,这些算法都可以轻易地被替换为另一个算法,这是策略模式的经典运用之一。策略模式的实现并不复杂,关键是如何从策略模式的实现背后,找到封装变化,委托和多态性这些思想的价值

5.5 更广义的“算法”

策略模式指的是定义一系列的算法,并且把它们封装起来

广义=>用来封装一系列的“业务规则”。

5.6 表单校验

例如

用户名不能为空

密码长度不能少于6位

手机号码必须符合格式

5.6.1 表单校验第一个版本

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="http://xxx.com/register" id="registerForm" method="post">
        请输入用户名:<input type="text" name="userName">
        请输入密码:<input type="text" name="password">
        请输入手机号码:<input type="text" name="phoneNumber">
        <button>提交</button>
    </form>
    <script>
        var registerForm = document.getElementById('registerForm');
        registerForm.onsubmit = function () {
            // body...
            if (registerForm.userName.value==='') {
                alert('用户名不能为空');
                return false;
            }
            if (registerForm.password.value.length<6) {
                alert('密码长度不能少于6位')
                return false;
            }
            if(!/(^1[3|5|8][0-9]{9}$)/.test(registerForm.phoneNumber.value)){
                alert('手机号码格式不正确')
                return false;
            }
        }
    </script>
</body>
</html>

registerForm.onsubmit函数比较庞大

rigisterForm.onsubmit函数缺乏弹性 违反开放-封闭原则

算法的复用性差

5.6.2 用策略模式重构表单重构表单校验

var strategies = {
    isNonEmpty:function(value,errorMsg){
        if (value==='') {
            return errorMsg;
        }
    },
    minLength:function(value,length,errorMsg){
        if (value.length<length) {
            return errorMsg;
        }

    },
    isMobile:function(value,errorMsg){
        if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
            return errorMsg;
        }
    }
}
//准备实现Validator类

var validataFunc = function(){
    var validator = new Validator();

    validator.add(registerForm.userName,'isNonEmpty','用户不能为空');
    validator.add(registerForm.password,'minLength:6','最小长度为6位');
    validator.add(registerForm.phoneNumber,'isMobile','手机号码格式不正确');

    var errorMsg = Validator.start();
    return errorMsg;
}

var registerForm = document.getElementById('registerForm');
registerForm.onsubmit = function(){
    var errorMsg = validataFunc();
    if (errorMsg) {
        alert(errorMsg);
        return false //阻止表单提交

    }
}

//Validator类的实现

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.value);  //unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度
        ary.push(errorMsg);
        return strategies[strategy].apply(dom,ary);
    });
};

Validator.prototype.start = function(){
    for(var i = 0,validataFunc;validataFunc = this.cache[i++];){
        var msg = validataFunc();
        if (msg) {
            return msg;
        }
    }
}

//so 修改某个校验规则

validator.sdd(registerForm.userName,'isNonEmpty','用户不能为空')

5.6.3 给某个文本输入框添加多种校验规则

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="http://xxx.com/register" id="registerForm" method="post">
        请输入用户名:<input type="text" name="userName">
        请输入密码:<input type="text" name="password">
        请输入手机号码:<input type="text" name="phoneNumber">
        <button>提交</button>
    </form>
    <script>
var strategies = {
    isNonEmpty:function(value,errorMsg){
        if (value==='') {
            return errorMsg;
        }
    },
    minLength:function(value,length,errorMsg){
        if (value.length<length) {
            return errorMsg;
        }

    },
    isMobile:function(value,errorMsg){
        if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
            return errorMsg;
        }
    }
}

//Validator类的实现

var Validator = function(){
    this.cache = [];
}

Validator.prototype.add = function(dom,rules){
    var self = this;

    for(var i = 0,rule;rule = rules[i++];){
        (function(rule){
            var strategyAry = rule.strategy.split(':');
            var errorMsg = rule.errorMsg;

            self.cache.push(function(){
                var strategy = strategyAry.shift();
                strategyAry.unshift(dom.value);
                strategyAry.push(errorMsg);
                return strategies[strategy].apply(dom,strategyAry);
            })
        })(rule)
    }

};

Validator.prototype.start = function(){
    for(var i = 0,validataFunc;validataFunc = this.cache[i++];){
        var errorMsg = validataFunc();
        if (errorMsg) {
            return errorMsg;
        }
    }
}
//准备实现Validator类

var validataFunc = function(){
    var validator = new Validator();

    validator.add(registerForm.userName,[{
        strategy:'isNonEmpty',errorMsg:'用户名不能为空'},{
        strategy:'minLength:10',errorMsg:'用户名不能小于10位'
    }]);
    validator.add(registerForm.password,[{strategy:'minLength:6',errorMsg:'最小长度为6位'}]);
    validator.add(registerForm.phoneNumber,[{strategy:'isMobile',errorMsg:'手机号码格式不正确'}]);

    var errorMsg = validator.start();
    return errorMsg;
}

var registerForm = document.getElementById('registerForm');
registerForm.onsubmit = function(){
    var errorMsg = validataFunc();
    if (errorMsg) {
        alert(errorMsg);
        return false //阻止表单提交

    }
}




    </script>
</body>
</html>

5.7 策略模式的有缺点

不严重的缺点

5.8 一等函数对象与策略模式

在Javascript中,“函数对象的多态性”来的更加简单

var s = function (salary) {
    // body...
    return salary*4;
}

var A = function(salary) {
    return salary*3;
}

var B = function(salary){
    return salary*2
}

var calculateBous = function(func,salary){
    return func(salary);
}

calculateBous(S,1000);
上一篇 下一篇

猜你喜欢

热点阅读