javascript策略模式的應用!

最近在看《JavaScript設計模式與開發實踐》這本書,受益不淺,小記錄一下書中的各個demo,加深理解;
策略模式的定義是:定義一系列的算法,把它們一個個封裝起來,而且使它們能夠相互替換。
案例1:不少公司的年終獎是根據員工的工資基數和年末績效狀況來發放的。例如,績效爲S 的人年終獎有4 倍工資,績效爲A 的人年終獎有3 倍工資,而績效爲B 的人年終獎是2 倍工資。假設財務部要求咱們提供一段代碼,來方便他們計算員工的年終獎。用JS實現這個很簡單html 代碼javascript

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

這個代碼是很是簡單的,可是缺點很明顯:
a、calculateBonus 函數比較龐大,包含了不少if-else 語句,這些語句須要覆蓋全部的邏輯分支。
b、calculateBonus 函數缺少彈性,若是增長了一種新的績效等級C,或者想把績效S 的獎金係數改成5,那咱們必須深刻calculateBonus 函數的內部實現,這是違反開放封閉原則的。
c、算法的複用性差,若是在程序的其餘地方須要重用這些計算獎金的算法呢?咱們的選擇只有複製和粘貼。
這個時候策略模式就用上場了;見代碼:
html 代碼css

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

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

案例二:實現一個js當中運動的DIV;
實用策略模式實現以下:
html 代碼html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>javascript策略模式的應用!</title>
</head>
<body>
<div style="position:absolute;background:blue; width: 100px;height: 100px;color: #fff;" id="div">我是div</div>
    <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 節點的位置,即dom 的初始位置
            this.endPos = 0; // 動畫結束時,dom 節點的位置,即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]; // dom 節點初始位置
            this.propertyName = propertyName; // dom 節點須要被改變的CSS 屬性名
            this.endPos = endPos; // dom 節點目標位置
            this.duration = duration; // 動畫持續事件
            this.easing = tween[easing]; // 緩動算法
            var self = this;
            var timeId = setInterval(function() { // 啓動定時器,開始執行動畫
                if (self.stop() === false) { // 若是動畫已結束,則清除定時器
                    clearInterval(timeId);
                }
            }, 19);
        };
        Animate.prototype.stop = function() {
            var t = +new Date; // 取得當前時間
            if (t >= this.startTime + this.duration) { // (1)
                this.update(this.endPos); // 更新小球的CSS 屬性值
                return false;
            }
            var pos = this.easing(t - this.startTime, this.startPos,
                this.endPos - this.startPos, this.duration);
            // pos 爲小球當前位置
            this.update(pos); // 更新小球的CSS 屬性值
        };
        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>
</body>
</html>

案列三:實現表單驗證;
html 代碼java

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">
</head>
<body>
    <form action="http:// xxx.com/register" id="registerForm" method="post">
    請輸入用戶名:<input type="text" name="userName"/ ><br>
    請輸入密碼:<input type="text" name="password"/ ><br>
     
    請輸入手機號碼:<input type="text" name="phoneNumber"/ ><br>
    <button>提交</button><br>
    </form>
<script>
    var registerForm = document.getElementById('registerForm');
    registerForm.onsubmit = function() {
        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>

這是一種很常見的代碼編寫方式,它的缺點跟計算獎金的最第一版本如出一轍。所以,仍是要使用策略模式; 代碼以下:
html 代碼算法

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">
</head>
<body>
    <form action="http:// xxx.com/register" id="registerForm" method="post">
    請輸入用戶名:<input type="text" name="userName"/ ><br>
    請輸入密碼:<input type="text" name="password"/ ><br>
     
    請輸入手機號碼:<input type="text" name="phoneNumber"/ ><br>
    <button>提交</button><br>
    </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, validatorFunc; validatorFunc = this.cache[i++];) {
            var errorMsg = validatorFunc();
            if (errorMsg) {
                return errorMsg;
            }
        }
    };
    /***********************客戶調用代碼**************************/
    var registerForm = document.getElementById('registerForm');
    var validataFunc = function() {
        var validator = new Validator();
        validator.add(registerForm.userName, [{
            strategy: 'isNonEmpty',
            errorMsg: '用戶名不能爲空'
        }, {
            strategy: 'minLength:6',
            errorMsg: '用戶名長度不能小於10 位'
        }]);
        validator.add(registerForm.password, [{
            strategy: 'minLength:6',
            errorMsg: '密碼長度不能小於6 位'
        }]);
        validator.add(registerForm.phoneNumber, [{
            strategy: 'isMobile',
            errorMsg: '手機號碼格式不正確'
        }]);
        var errorMsg = validator.start();
        return errorMsg;
    }
    registerForm.onsubmit = function() {
        var errorMsg = validataFunc();
        if (errorMsg) {
            alert(errorMsg);
            return false;
        }
    };
</script>
</body>
</html>

策略模式是一種經常使用且有效的設計模式,本章提供了計算獎金、緩動動畫、表單校驗這三個例子來加深你們對策略模式的理解。從這三個例子中,咱們能夠總結出策略模式的一些優勢。
a、策略模式利用組合、委託和多態等技術和思想,能夠有效地避免多重條件選擇語句。
b、策略模式提供了對開放—封閉原則的完美支持,將算法封裝在獨立的strategy 中,使得它們易於切換,易於理解,易於擴展。
c、策略模式中的算法也能夠複用在系統的其餘地方,從而避免許多重複的複製粘貼工做。
固然,策略模式也有一些缺點,但這些缺點並不嚴重。可略過。。設計模式

相關文章
相關標籤/搜索