如果你厌烦了大量的 if else, 那么你可以来看看策略模式
假设有这样一个场景
- env 等于 'dev', 则使用 'http://localhost:8080/'
- env 等于 'prod', 则使用 'http://xxx.xxx/'
function getUrl(env) {
if (env === 'dev') {
return 'http://localhost:8080/'
}
if (env === 'prod') {
return 'http://xxx.xxx/'
}
}
很容易想到 if else 几下解决
有两点明显的问题:
- 违反了单一职责, 一个 function 中有多种逻辑
- 违反了开闭原则, 有新需求的时候, 比如添加 test 环境, 需要改动原代码
使用策略模式改造下
function urlProcessor = {
dev() {
return 'http://localhost:8080/'
},
prod() {
return 'http://xxx.xxx/'
}
}
// 新增需求
urlProcessor.test = () => {
return 'http://xxx.xxx/test'
}
// 调用
urlProcessor[env]()