JavaScript策略模式应用

最近在看《JavaScript设计模式与开发实践》这本书,受益匪浅,小记录一下书中的各个demo,加深理解。

将不变的部分与变化的部分隔开是每个设计模式的主题,策略模式也不例外,策略模式的目的就是将算法的使用与算法的实现分离开来。

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

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

demo1:

很多公司的年终奖是根据员工的工资基数和年底绩效情况来发放的。例如,绩效为S 的人年终奖有4 倍工资,绩效为A 的人年终奖有3 倍工资,而绩效为B 的人年终奖是2 倍工资。假设财务部要求我们提供一段代码,来方便他们计算员工的年终奖。用JS实现这个很简单:

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

通过使用上面策略模式重构代码,我们消除了原程序中大片的条件分支语句。所有跟计算奖金有关的逻辑不再放在Context中,而是分布在各个策略对象中。Context并没有计算奖金的能力,而是把这个职责委托给了某个策略对象,每个策略对象负责的算法已被各自封装在对象内部。

demo2 实现一个js当中运动的DIV:

使用策略模式实现如下:

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

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

发布了398 篇原创文章 · 获赞 182 · 访问量 37万+

猜你喜欢

转载自blog.csdn.net/yexudengzhidao/article/details/105505344