常见的改善前端代码的设计模式-策略模式

基本概念

定义:定义一系列的算法, 把它们一个个封装起来, 并且使它们可以相互替换。
使用场景:达到某个目的,有不同的方法。例如表单校验。
关键:环境类(context)接受某一请求,随后把某一请求委托给一策略类,context需要维持对某一策略对象的引用。
名词解释:环境类:接受客户请求的类;策略类:实现具体算法的类

模仿面向对象语言的代码实现

jscode

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
// 策略类
var muneA = function () {}
muneA.prototype.calculate = function (count) {
return count * 100
}
var muneB = function () {}
muneB.prototype.calculate = function (count) {
return count * 1000
}
var muneC = function () {}
muneC.prototype.calculate = function (count) {
return count * 500
}

// 环境类
var Checkstand = function () {
this.count = null
this.strategy = nul;

}

Checkstand.prototype.setCount = function (count) {
this.count = count
}

Checkstand.prototype.setStrategy = function (strategy) {
this.strategy = strategy
}
Checkstand.prototype.getDealMoney = function () {
return this.strategy.calculate(this.strategy)
}

// 调用
var checkstand = new Checkstand()
checkstand.setStrategy(new muneA()) // 设置策略对象
checkstand.setCount(10) // 设置数量

根据js语言特性的代码实现

jscode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var strategy = {
"muneA": function (count) {
return count * 100
},
"muneB": function (count) {
return count * 1000
},
"muneC": function (count) {
return count * 500
},
}

// 使用
var calculateDelaMoney = function (menuType, count) {
return strategy[menuType](count)
}