设计模式之策略模式

什么是策略模式

策略模式说白了就是要实现某一个功能,有多种方案可以选择。我们定义一系列的算法,把它们一个个封装起来,并且使它们可以相互转换。

真实的例子

既然提到具体的功能,那只能通过开发常遇到的一些案例去解读策略模式

比如我们要给一个公司开发一个年终奖发奖励的功能:

当绩效类型为“S”时,4个月的奖金
当绩效类型为“A”时,3个月奖金
当绩效类型为“B”时,2个月奖金

//我们很容易就想到用performanceLevel, salary分别代表绩效等级和基本月工资。然后大致的代码如下
var calculateBonus = function(performanceLevel, salary) {
  if (performanceLevel === 'S') {
    return salary * 4;
  }
  if (performanceLevel === 'A') {
    return salary * 3;
  }
  if (performanceLevel === 'B') {
    return salary * 2;
  }
};
console.log(calculateBonus('B', 20000)); // 输出:40000 
console.log(calculateBonus('S', 6000)); // 输出:24000

// 一看没问题吧,功能都实现了,if-else侠有下面两个缺点

  1. calculateBonus 函数既进行了等级判断,又返回了绩效奖金,违背了函数的“单一功能”原则'
  2. 不仅如此,它还违背了“开放封闭”原则,假设哪一天老板又要加个SSS级绩效给自己秘书咋办,咱不得改动这个主体函数。
    根据上面的问题,结合我们学习的设计模式去改造函数

函数的改造

单一功能原则

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

再思考一下,我们是遵循了单一功能原则,但是每次新增一个performanceLevel时,我们还是要去改calculateBonus 这个函数,现在我们的需求是

S---> salary * 4
A---> salary * 3
B---> salary * 2

这么一想,我们是不是很容易就想到了映射关系,那么常用的映射不就是对象的键值对嘛

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

这样我们再也不用担心老板要给多少个秘书添加绩效了

strategies['sss'] = function(salary) {
    return salary * 1314520;
  }
 ...

我们也可以直接用重构代码

var performanceS = function (){}
performanceS.prototype.calculate = function(salary){
  return salary*4
};
var performanceA = function (){}
performanceS.prototype.calculate = function(salary){
  return salary*3
};
var performanceB = function (){}
performanceS.prototype.calculate = function(salary){
  return salary*2
};
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

下面顺便附上es6 class的写法

// 定义策略类
class performanceS {
  calculate(salary) {
    return salary * 4;
  }
}

class performanceA {
  calculate(salary) {
    return salary * 3;
  }
}

class performanceB {
  calculate(salary) {
    return salary * 2;
  }
}

// 定义奖金类
class Bonus {
  constructor() {
    this.salary = null; // 原始工资
    this.strategy = null; // 对应的策略对象
  }

  // 设定原始工资
  setSalary(salary) {
    this.salary = salary;
  }

  // 设置员工绩效等级对应的策略对象
  setStrategy(strategy) {
    this.strategy = strategy;
  }

  getBonus() {
    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

下面我们实现一个form表单提交的多条件校验的例子

<html>
 <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, 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>
posted @ 2021-11-17 14:58  自在一方  阅读(48)  评论(0编辑  收藏  举报