Home >Web Front-end >JS Tutorial >Learn JavaScript design pattern (strategy pattern)_javascript skills

Learn JavaScript design pattern (strategy pattern)_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:29:401066browse

What is strategy? For example, if we want to travel somewhere, we can choose the route based on the actual situation.
1. Definition of strategy pattern

If you don’t have time but don’t care about money, you can choose to fly.
If you don’t have money, you can choose to take a bus or train.
If you are poorer, you can choose to ride a bicycle.
In programming, we often encounter similar situations. There are many options to choose from to implement a certain function. For example, a program that compresses files can choose either the zip algorithm or the gzip algorithm.

Definition: The strategy pattern defines a series of algorithms, which are encapsulated separately so that they can be replaced with each other. This pattern makes the algorithm changes independent of the customers who use Suanfan .

The strategy pattern has a wide range of applications. In this section, we will take the calculation of year-end bonus as an example.

2. Year-end bonus examples

Many companies’ year-end bonuses are based on employees’ salary base and performance at the end of the year. For example, the year-end bonus of a person with performance S is 4 times the salary, the year-end bonus of a person with performance A is 3 times the salary, and the year-end bonus of a person with performance B is 2 times the salary. Suppose the finance department asks us to provide a piece of code to facilitate their calculation of employees' year-end bonuses.

1). Initial code implementation

We can write a function called calculateBonus to calculate the bonus amount for each person. Obviously, for the calculateBonus function to work correctly, it needs to receive two parameters: the employee's salary amount and his performance appraisal grade. The code is as follows:

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

It can be found that this code is very simple, but it has obvious shortcomings.

calculateBonus function is relatively large, contains many if-else statements, which need to cover all logical branches.

The calculateBonus function is inflexible. If a new performance level C is added, or we want to change the bonus coefficient of performance S to 5, then we must go deep into the internal implementation of the calculateBonus function, which is a violation Open-closed principle.

The reusability of the algorithm is poor. What if these algorithms for calculating bonuses need to be reused elsewhere in the program? Our only options are copy and paste. Therefore, we need to refactor this code.

2). Refactor the code using combined functions

Generally the easiest way to think of is to use combination functions to reconstruct it. We encapsulate various algorithms into small functions. These small functions are well-named, and you can know at a glance which algorithm they correspond to. , they can also be reused elsewhere in the program. The code is as follows:

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

Currently, our program has been improved to some extent, but this improvement is very limited. We still have not solved the most important problem: the calculateBonus function may become larger and larger, and it lacks flexibility when the system changes.

3). Use strategy pattern to refactor code

After thinking about it, we came up with a better way - using strategy pattern to refactor the code. The strategy pattern refers to defining a series of algorithms and encapsulating them one by one. Separating the unchanged parts from the changing parts is the theme of every design pattern, and the strategy pattern is no exception. The purpose of the strategy pattern is to separate the use of the algorithm from the implementation of the algorithm.

In this example, the method of using the algorithm remains the same, and the calculated bonus amount is obtained based on a certain algorithm. The implementation of algorithms is different and changing, and each performance corresponds to different calculation rules.

A program based on the strategy pattern consists of at least two parts. The first part is a set of strategy classes. The strategy class encapsulates specific algorithms and is responsible for the specific calculation process. The second part is the environment class Context. Context accepts the customer's request and then delegates the request to a certain strategy class. To do this, it means that a reference to a policy object must be maintained in the Context.

Now use the strategy pattern to refactor the above code. The first version was modeled after implementation in traditional object-oriented languages. We first encapsulate each performance calculation rule in the corresponding strategy class:

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

Next define the bonus type 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 ); //把计算奖金的操作委托给对应的策略对象
};

在完成最终的代码之前,我们再来回顾一下策略模式的思想:

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

这句话如果说得更详细一点,就是:定义一系列的算法,把它们各自封装成策略类,算法被封装在策略类内部的方法里。在客户对Context发起请求的时候,Context总是把请求委托给这些策略对象中间的某一个进行计算。

“并且使它们可以相互替换”,这句话在很大程度上是相对于静态类型语言而言的。因为静态类型语言中有类型检查机制,所以各个策略类需要实现同样的接口。当它们的真正类型被隐藏在接口后面时,它们才能被相互替换。而在JavaScript这种“类型模糊”的语言中没有这种困扰,任何对象都可以被替换使用。因此,JavaScript中的“可以相互替换使用”表现为它们具有相同的目标和意图。

现在我们来完成这个例子中剩下的代码。先创建一个bonus对象,并且给bonus对象设置一些原始的数据,比如员工的原始工资数额。接下来把某个计算奖金的策略对象也传入bonus对象内部保存起来。当调用bonus.getBonus()来计算奖金的时候,bonus对象本身并没有能力进行计算,而是把请求委托给了之前保存好的策略对象:

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

在5.1节中,我们让strategy对象从各个策略类中创建而来,这是模拟一些传统面向对象语言的实现。实际上在JavaScript语言中,函数也是对象,所以更简单和直接的做法是把strategy直接定义为函数:

var strategies = {
 "S": function( salary ){
 return salary * 4;
 },
 "A": function( salary ){
 return salary * 3;
 },
 "B": function( salary ){
 return salary * 2;
 }
}; 

同样,Context也没有必要必须用Bonus类来表示,我们依然用calculateBonus 函数充当Context来接受用户的请求。经过改造,代码的结构变得更加简洁:

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

3、实例再讲解

一个小例子就能让我们一目了然。
回忆下jquery里的animate方法.

$( div ).animate( {"left: 200px"}, 1000, 'linear' ); 
//匀速运动
$( div ).animate( {"left: 200px"}, 1000, 'cubic' ); 
//三次方的缓动

这2句代码都是让div在1000ms内往右移动200个像素. linear(匀速)和cubic(三次方缓动)就是一种策略模式的封装.

再来一个例子. 很多页面都会有个即时验证的表单. 表单的每个成员都会有一些不同的验证规则.

比如姓名框里面, 需要验证非空,敏感词,字符过长这几种情况。 当然是可以写3个if else来解决,不过这样写代码的扩展性和维护性可想而知。如果表单里面的元素多一点,需要校验的情况多一点,加起来写上百个if else也不是没有可能。

所以更好的做法是把每种验证规则都用策略模式单独的封装起来。需要哪种验证的时候只需要提供这个策略的名字。就像这样:

nameInput.addValidata({
 notNull: true,
 dirtyWords: true,
 maxLength: 30
})
而notNull,maxLength等方法只需要统一的返回true或者false,来表示是否通过了验证。

validataList = {
 notNull: function( value ){
 return value !== '';
 },
 maxLength: function( value, maxLen ){
 return value.length() > maxLen;
 }
}

可以看到,各种验证规则很容易被修改和相互替换。如果某天产品经理建议字符过长的限制改成60个字符。那只需要0.5秒完成这次工作。

大概内容就为大家介绍到这。

聊一聊题外话,马上2015年要过去了,大家的年终奖是不是很丰厚呀!!!

希望大家可以在这一年里有所收获,通过这篇文章也能有所收获,知道什么是策略模式,理解小编精心为大家准备的两个实例。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn