定义
策略模式就是定义一系列的算法,将他们一个个封装起来。
使用场景
在实际开发中,我们需要将算法的含义扩大一些。
比如,策略模式可以有效的拆分 业务逻辑,减少代码中的if .... else....
这种分支
假设我们有一个按钮。需要根据 api 提供的不同状态渲染不同的内容, 且做不同的逻辑处理。
根据策略模式的思想,我们可以像下面这样写
const strategies = {
"1": {
text: '借钱',
action: () => {
// go to withdraw page and do somthing
},
},
"2": {
text: '还钱',
action: () => {
// go to payback page and do somthing
},
},
"3": {
text: '授信',
action: () => {
// go to witcredithdraw page and do somthing
},
},
}
const Demo = () => {
const [status, setStatus] = useState('3');
useEffect(() => {
fetch(...)
.then(res.json())
.then((data) => {
setStatus(data.status)
})
}, [])
handleClick = () => {
// Context
strategies[status].action()
}
return (
<div>
<div>header</div>
<button onClick={handleClick}>{strategies[status].text}</button>
</div>
)
}
优缺点
- 策略模式利用组合、委托、多态等技术和思想,可以有效的减少代码中的
if ... else ...
多层判断 - 易于理解,容易扩展。如上,如果有新的状态。我们只需要在
strategies
中增加对应的算法
- 解放
Context(看代码注释部分)
, 只让Context
拥有执行算法的能力。而不是将更多的逻辑堆砌在Context
中