JavaScript设计模式7策略模式

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

从定义可以看出,策略模式至少需要两部分。一部分是策略类,封装具体算法,负责具体的计算过程。一部分是环境类context,context接受客户请求,并将请求委托给某个策略类。

传统面向对象实现方式:

var performanceS = function(){}
performanceS.prototype.calculate = function(salary){
	return salary * 4;
}

var bonus = function(){
	this.strategy = null;
	this.salary = 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(1000)
bonus.setStrategy(new performanceS())

javascript的策略模式实现:

var strategies = {
	's' : function(salary){
		return salary *400;
	}
}

var calculateBonus= function(strategy){
	return strategies[strategy](salary)
}

calculateBonus('s', 1000)
//在函数作为一等对象的语言中,策略模式是隐形的
var s = function(salary){
	return salary * 400;
}

var getBonus = function(fn,salary){
	return fn(salary);
}

getBonus(s, 100);

  

posted @ 2016-02-18 11:39  倾其一生  阅读(94)  评论(0编辑  收藏  举报