策略模式(上)

所谓策略模式就是定义一系列的算法,把他们一个个封装起来,并且他们可以互相替换
具体来说:定义一系列的算法,把他们各自封装成策略类,算法被封装在策略类内部。客户对Context发起请求时,Context总是把请求委托给这些策略类中间的某一个进行计算

接下来我们来看一个实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//未使用策略模式计算奖金
var calculateBouns = function(performanceLever,salary){
if( performanceLever === 'S'){
return salary * 4
}

if( performanceLever === 'A'){
return salary * 3
}

if( performanceLever === 'B'){
return salary * 2
}
}

console.log( calculateBouns( 'S',1000 ) ); //4000
console.log( calculateBouns( 'B',1000 ) ); //2000
console.log( calculateBouns( 'A',1000 ) ); //3000

这样子写存在很多缺点:

  • calculateBouns函数庞大,包含太多if...else
  • 函数缺乏弹性,如果继续增加一个考核等级,就必须在函数里面添加,违反开放封闭原则
  • 算法复用性差,很难复用到其他地方

接下来,我们就用策略模式来重构该例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//策略类:
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;
}

// 使用环境
var Bouns = function(){
this.salary = null;
this.strategy = null;
};

Bouns.prototype.setSalary = function(salary){
this.salary = salary;
}

Bouns.prototype.setStrategy = function(strategy){
this.strategy = strategy;
}

Bouns.prototype.getBouns = function(){
return this.strategy.calculate( this.salary )
}

var bouns = new Bouns();
bouns.setSalary('1000');
bouns.setStrategy( new performanceS() );
console.log( bouns.getBouns() ); //4000

bouns.setStrategy( new performanceA() );
console.log( bouns.getBouns() ) //3000

首先我们需要定义一个策略类,把有关计算奖金的算法逻辑及实现封装在其中,然后需要一个环境类,来接受客户的请求,并将请求委托给策略类,从而实现功能,注意:Content里面要维持对一个策略类的引用

以上是基于面向对象来书写的,在JS中,函数也是对象,所以接下来我们来看看JS版本的策略模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var strategy = {			//通过对象字面量的形式类把各个类写在其中
'S':function(salary){
return salary*4;
},
'A':function(salary){
return salary * 3;
},
'B':function(salary){
return salary * 2;
}
};

var calculate = function(performanceLever,salary){
return strategy[performanceLever](salary);
};

console.log(calculate('S',1000)) //4000
console.log( calculate('A',2000) ) //6000

好,现在我们大致了解了策略模式大概长成啥样了,接下来,欲知后事如何,请听下回分解^_^

文章目录