设计模式之策略模式

参考资料


  • 曾探《JavaScript设计模式与开发实践》;

定义


定义一系列的算法,把他们一个个封装起来,并且使它们可以相互替换。封装算法、封装“业务规则”。

在函数作为一等对象的语言中,策略模式是隐形的。strategy就是作为函数的变量。在JavaScript中,除了使用类来封装算法和行为之外,使用函数当然也是一种选择。这些“算法”可以被封装在函数中并且四处传递,也就是我们常说的“高阶函数”。

使用场景:

  • 计算奖金;

  • 动画;

  • 校验用户输入的数据,比如async-validator;

计算奖金


  • 使用策略模式前:

    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
  • 使用策略模式重构代码:

  • 面向对象版本的策略模式:

    var performanceS = function(){};
    performanceS.prototype.calculate = function( salary ){
        return salary * 4;
    };
    var performanceA = function(){};
    performanceA.prototype.calculate = function( salary ){
        return salary * 3;
    };
    var performanceB = function(){};
    performanceB.prototype.calculate = function( salary ){
        return salary * 2;
    };
​
    //接下来定义奖金类Bonus:
​
    var Bonus = function(){
        this.salary = null; // 原始工资
        this.strategy = null; // 绩效等级对应的策略对象
    };
    Bonus.prototype.setSalary = function( salary ){
        this.salary = salary; // 设置员工的原始工资
    };
    Bonus.prototype.setStrategy = function( strategy ){
        this.strategy = strategy; // 设置员工绩效等级对应的策略对象
    };
    Bonus.prototype.getBonus = function(){ // 取得奖金数额
        return this.strategy.calculate( this.salary ); // 把计算奖金的操作委托给对应的策略对象
    };
​
    var bonus = new Bonus();
    bonus.setSalary( 10000 );
​
    bonus.setStrategy( new performanceS() ); // 设置策略对象
    console.log( bonus.getBonus() ); // 输出:40000
    bonus.setStrategy( new performanceA() ); // 设置策略对象
    console.log( bonus.getBonus() ); // 输出:30000
  • JavaScript版本的策略模式:

    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

表单验证


  • 使用策略模式前:

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;
        }
    }
  • 使用策略模式重构:

        /***********************策略对象**************************/
        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 位'
            }]);
            var errorMsg = validator.start();
            return errorMsg;
        }
        registerForm.onsubmit = function(){
            var errorMsg = validataFunc();
            if ( errorMsg ){
                alert ( errorMsg );
                return false;
            }
        };

策略模式的优缺点


  • 优点:

  • 策略模式利用组合、委托和多态等技术和思想,可以有效的避免多重条件选择语句。

  • 策略模式提供了对开发-封闭原则的完美支持,将算法封装在独立的strategy中,使得它们易于切换,易于理解,易于扩展。

  • 策略模式中的算法也可以复用在系统的其他地方,从而避免许多重复的复制粘贴工作。

  • 在策略模式中利用组合和委托来让Context拥有执行算法的能力,这也是继承的一种更轻便的替代方案。

  • 缺点:

  • 使用策略模式会在程序中增加许多策略类或者策略对象,但这实际上这比把它们负责的逻辑堆砌在Context中要好。

  • 要使用策略模式,必须要了解所有的strategy,必须了解各个strategy之间的不同点,这样才能选择一个合适的strategy。比如,我们要选择一种合适的旅行出行路线,必须先了解选择飞机、火车、自行车等方案的细节。此时strategy要向客户暴露它的所有实现,这是违反最少知识原则的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值