js设计模式--策略模式

7,776 阅读9分钟

前言

本系列文章主要根据《JavaScript设计模式与开发实践》整理而来,其中会加入了一些自己的思考。希望对大家有所帮助。

文章系列

js设计模式--单例模式

js设计模式--策略模式

js设计模式--代理模式

概念

策略模式的定义是:定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换

策略模式指的是定义一系列的算法,把它们一个个封装起来。将不变的部分和变化的部分隔开是每个设计模式的主题,策略模式也不例外,策略模式的目的就是将算法的使用与算法的实现分离开来

一个基于策略模式的程序至少由两部分组成。第一个部分是一组策略类,策略类封装了具体 的算法,并负责具体的计算过程。 第二个部分是环境类Context,Context 接受客户的请求,随后 把请求委托给某一个策略类。要做到这点,说明 Context中要维持对某个策略对象的引用。

策略模式的实现并不复杂,关键是如何从策略模式的实现背后,找到封装变化、委托和多态性这些思想的价值。

场景

从定义上看,策略模式就是用来封装算法的。但如果把策略模式仅仅用来封装算法,未免有一点大材小用。在实际开发中,我们通常会把算法的含义扩散开来,使策略模式也可以用来封装 一系列的“业务规则”。只要这些业务规则指向的目标一致,并且可以被替换使用,我们就可以 用策略模式来封装它们。

优缺点

优点

  • 策略模式利用组合、委托和多态等技术和思想,可以有效地避免多重条件选择语句。
  • 策略模式提供了对开放—封闭原则的完美支持,将算法封装在独立的strategy中,使得它们易于切换,易于理解,易于扩展。
  • 策略模式中的算法也可以复用在系统的其他地方,从而避免许多重复的复制粘贴工作。
  • 在策略模式中利用组合和委托来让 Context 拥有执行算法的能力,这也是继承的一种更轻便的替代方案。

缺点

  • 增加许多策略类或者策略对象,但实际上这比把它们负责的 逻辑堆砌在 Context 中要好。
  • 要使用策略模式,必须了解所有的 strategy,必须了解各个 strategy 之间的不同点, 这样才能选择一个合适的 strategy。

但这些缺点并不严重

例子

计算奖金

粗糙的实现

	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

缺点:

  1. calculateBonus 函数比较庞大,包含了很多 if-else 语句
  2. calculateBonus 函数缺乏弹性,如果增加了一种新的绩效等级 C,或者想把绩效 S 的奖金 系数改为 5,那我们必须深入 calculateBonus 函数的内部实现,这是违反开放封闭原则的。
  3. 算法的复用性差

使用组合函数重构代码


	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 );
		}
	};
	calculateBonus( 'A' , 10000 ); // 输出:30000

问题依然存在:calculateBonus 函数有可能越来越庞大,而且在系统变化的时候缺乏弹性

使用策略模式重构代码


	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实现的策略模式。

JavaScript 版本的策略模式

在 JavaScript 语言中,函数也是对象,所以更简单和直接的做法是把 strategy 直接定义为函数

	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

es6类实现


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:
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

缓动动画

目标:编写一个动画类和一些缓动算法,让小球以各种各样的缓动效果在页面中运动

分析:

首先缓动算法的职责是实现小球如何运动

然后动画类(即context)的职责是负责:

  1. 初始化动画对象

    在运动开始之前,需要提前记录一些有用的信息,至少包括以下信息:

    • 动画开始时的准确时间点;
    • 动画开始时,小球所在的原始位置;
    • 小球移动的目标位置;
    • 小球运动持续的时间。
  2. 计算小球某时刻的位置

  3. 更新小球的位置

实现:


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div style="position:absolute;background:blue" id="div">我是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 节点的位置,即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.step() === false) { // 如果动画已结束,则清除定时器
        clearInterval(timeId);
      }
    }, 16);
  };

  Animate.prototype.step = 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, 'linear');
  // animate.start( 'top', 1500, 500, 'strongEaseIn' );
</script>

</html>

验证表单

简单的实现


<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 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>

<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;
        }
      }
    };

    var validataFunc = function () {
      var validator = new Validator(); // 创建一个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(); // 如果errorMsg 有确切的返回值,说明未通过校验
      if (errorMsg) {
        alert(errorMsg);
        return false; // 阻止表单提交
      }
    };

    var Validator = function () {
      this.cache = []; // 保存校验规则
    };

    Validator.prototype.add = function (dom, rule, errorMsg) {
      var ary = rule.split(':'); // 把strategy 和参数分开
      this.cache.push(function () { // 把校验的步骤用空函数包装起来,并且放入cache
        var strategy = ary.shift(); // 用户挑选的strategy
        ary.unshift(dom.value); // 把input 的value 添加进参数列表
        ary.push(errorMsg); // 把errorMsg 添加进参数列表
        return strategies[strategy].apply(dom, ary);
      });
    };

    Validator.prototype.start = function () {
      for (var i = 0, validatorFunc; validatorFunc = this.cache[i++];) {
        var msg = validatorFunc(); // 开始校验,并取得校验后的返回信息
        if (msg) { // 如果有确切的返回值,说明校验没有通过
          return msg;
        }
      }
    };
  </script>
</body>

</html>

缺点:一 个文本输入框只能对应一种校验规则

再改进:可以有多个校验规则

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

    };
  </script>
</body>

</html>