策略模式
策略模式有时是违法最少知识原则的,因为使用者可能要了解所有的 strategy 才能判断应该具体使用哪种 strategy。
例1:
javascript
const strategy = new SomeStrategy()
context.setStrategy(strategy)
context.doSomething()
1
2
3
2
3
例2:
javascript
const eventStrategies = {
commandStart: {
editor: async () => {},
},
commandEnd: {
editor: async () => {},
},
*: async () => {}
}
addEventListener((type, msg) => {
const strategy = eventStrategies[type][msg]
if (typeof strategy === 'function') {
strategy()
return
}
eventStrategies['*']()
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17