当前位置:网站首页>利用策略模式优化if代码【策略模式】
利用策略模式优化if代码【策略模式】
2022-07-04 17:16:00 【qq_22841387】
问题描述
当前我们代码中存在很多的if,else去控制程序的流程,但是这样就会导致一个问题——代码的可扩展性不高。
这里以策略模式进行对if-else代码的优化
实现过程
1.定义策略模式类型
/** 通用类型 */
export namespace Common {
/** * 策略模式 * - 状态 * - true时执行的函数 */
type StrategyAction = [boolean, () => void];
}
参数中,左侧是boolean类型,右侧是对应的响应函数
2.执行策略模式函数
import {
Common } from "@/types/common/common"
export function exeStrategyActions(actions: Common.StrategyAction[]) {
actions.some((item) => {
const [flag, action] = item
if (flag) {
action()
}
return flag
})
}
通过
some
去执行策略模式,当对应策略模式类型中的flag
为true时,执行对应的方法
some的官方定义
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn’t modify the array.
解释:
这个some方法测试是否数组中至少有一个通过提供的函数。将它变为ture,如果它找到了一个元素符合提供的函数;否则变为false。它不会改变原本数组
也就是说,当some找到了第一个满足的条件后,就不再执行后续方法
3.实例使用
const action :Common.StrategyAction[] = [
[
value === '首页',
() => {
useRouterPush().routerPush('home')
},
],
[
value === '提交列表',
() => {
submitListModal.openModal()
},
],
]
exeStrategyActions(action)
- 当
value
为首页时,执行跳转路由方法 - 当
value
为提交列表时,打开拟态框
边栏推荐
猜你喜欢
能源行业的数字化“新”运维
Li Kou brush question diary /day2/2022.6.24
Crawler (6) - Web page data parsing (2) | the use of beautifulsoup4 in Crawlers
MySQL常用增删改查操作(CRUD)
线上MySQL的自增id用尽怎么办?
蓝桥:合根植物
Unity makes revolving door, sliding door, cabinet door drawer, click the effect of automatic door opening and closing, and automatically play the sound effect (with editor extension code)
Basic tutorial of scala -- 16 -- generics
力扣刷题日记/day7/6.30
【2022年江西省研究生数学建模】冰壶运动 思路分析及代码实现
随机推荐
6.26CF模拟赛E:价格最大化题解
一直以为做报表只能用EXCEL和PPT,直到我看到了这套模板(附模板)
How is the entered query SQL statement executed?
Scala basic tutorial -- 14 -- implicit conversion
NBA赛事直播超清画质背后:阿里云视频云「窄带高清2.0」技术深度解读
力扣刷题日记/day7/6.30
Thawte通配符SSL证书提供的类型有哪些
同事悄悄告诉我,飞书通知还能这样玩
Deleting nodes in binary search tree
发送和接收IBM WebSphere MQ消息
C语言打印练习
Wireshark packet capturing TLS protocol bar displays version inconsistency
How is the entered query SQL statement executed?
Is it safe to open an account online? is that true?
网上开户安全吗?是真的吗?
[go ~ 0 to 1] read, write and create files on the sixth day
TorchDrug教程
基于C语言的菜鸟驿站管理系统
Lua EmmyLua 注解详解
谷粒商城(一)