策略模式

状态模式

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
let ResultState = (() => {
let States = {
state0: function () {
console.log("state0")
},
state1: function () {
console.log("state1")
},
state2: function () {
console.log("state2")
},
state3: function () {
console.log("state3")
},
}

function show(result) {
States["state" + result] && States["state" + result]()
}

return {
show,
}
})()

// for test
ResultState.show(3)

策略模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let Price = (() => {
let obj = {
return30: (price) => +price + parseInt(price / 100) * 30,
return50: (price) => +price + parseInt(price / 100) * 50,
percent90: (price) => (price * 100 * 90) / 10000,
percent80: (price) => (price * 100 * 80) / 10000,
}
return (algorithm, price) => {
return obj[algorithm] && obj[algorithm](price)
}
})()

// for test
let price = Price("return50", 321.13)
console.log(price)