当前位置: 首页 > news >正文

代码中的设计模式-策略模式

假如我们有一段代码,有很多的if else

function executeAction(type) {if (type === 'A') {console.log('Action A');} else if (type === 'B') {console.log('Action B');} else if (type === 'C') {console.log('Action C');} else {console.log('Unknown action');}
}executeAction('A'); // 输出: Action A
executeAction('B'); // 输出: Action B
executeAction('C'); // 输出: Action C
executeAction('D'); // 输出: Unknown action

如果if else有很多很多, 那么代码就会变的非常不直观且难以维护

那对于这种情况有什么好的解决办法吗
这就引出了我们今天的主角: 策略模式

什么是策略模式

策略模式(Strategy Pattern)是一种行为设计模式,它允许你定义一系列算法或行为,并将它们封装在独立的策略类中。然后,你可以根据需要在运行时选择不同的策略。这种模式特别适合处理复杂的条件逻辑,比如多个 if-else if 语句。

下面来看使用策略模式的解决方案

我们可以将每个条件分支封装在一个策略类中,然后在运行时选择合适的策略。

// 定义策略接口
class Strategy {execute() {throw new Error('You have to implement the method execute!');}
}// 具体策略A
class StrategyA extends Strategy {execute() {console.log('Action A');}
}// 具体策略B
class StrategyB extends Strategy {execute() {console.log('Action B');}
}// 具体策略C
class StrategyC extends Strategy {execute() {console.log('Action C');}
}// 默认策略
class DefaultStrategy extends Strategy {execute() {console.log('Unknown action');}
}// 策略上下文
class Context {constructor() {this.strategies = {'A': new StrategyA(),'B': new StrategyB(),'C': new StrategyC()};}executeAction(type) {const strategy = this.strategies[type] || new DefaultStrategy();strategy.execute();}
}// 使用策略模式
const context = new Context();
context.executeAction('A'); // 输出: Action A
context.executeAction('B'); // 输出: Action B
context.executeAction('C'); // 输出: Action C
context.executeAction('D'); // 输出: Unknown action

策略接口 (Strategy): 定义了一个 execute 方法,所有具体的策略类都必须实现这个方法。

具体策略类 (StrategyA, StrategyB, StrategyC, DefaultStrategy): 每个类都实现了 execute 方法,执行特定的操作。

策略上下文 (Context): 维护一个策略对象的映射,并根据传入的 type 选择合适的策略来执行。如果没有找到对应的策略,则使用默认策略。

使用策略模式: 通过 Context 类的 executeAction 方法来执行不同的策略。

这样实现有哪些好处

可扩展性: 如果需要添加新的策略,只需添加一个新的策略类,并在 Context 中注册即可,无需修改现有代码。

代码清晰: 将复杂的条件逻辑分解到不同的策略类中,使代码更易于理解和维护。

灵活性: 可以在运行时动态地选择不同的策略,而不需要修改代码。

http://www.lryc.cn/news/479673.html

相关文章:

  • 后端Node学习项目-项目基础搭建
  • Python | Leetcode Python题解之第538题把二叉搜索树转换为累加树
  • 【ZeroMQ 】ZeroMQ中inproc优势有哪些?与其它传输协议有哪些不同?
  • spark的学习-03
  • 一文了解Android SELinux
  • 数据血缘追踪是如何在ETL过程中发挥作用?
  • 跟我学C++中级篇——生产中如何调试程序
  • Python爬虫实战 | 爬取网易云音乐热歌榜单
  • apk因检测是否使用代理无法抓包绕过方式
  • DevOps业务价值流:架构设计最佳实践
  • 计算机网络——SDN
  • 开源数据库 - mysql - innodb源码阅读 - master线程(一)
  • vscode ssh连接autodl失败
  • 文件系统和日志管理 附实验:远程访问第一台虚拟机日志
  • 云上拼团GO指南——腾讯云博客部署案例,双11欢乐GO
  • 【VScode】VScode内的ChatGPT插件——CodeMoss全解析与实用教程
  • 水库大坝安全监测预警方法
  • 深度学习:微调(Fine-tuning)详解
  • qt QWebSocketServer详解
  • 【数据结构】线性表——链表
  • Fork突然报错
  • Vue Element-UI 选择隐藏表格中的局部字段信息
  • easyui +vue v-slot 注意事项
  • vue之组件网站(后续补)
  • 大模型的常用指令格式 --> ShareGPT 和 Alpaca (以 llama-factory 里的设置为例)
  • 【论文阅读】火星语义分割的半监督学习
  • ACM社团第一次测试题解(禁止直接复制粘贴提交)
  • redis:zset有序集合命令和内部编码
  • Day107:代码审计-PHP模型开发篇MVC层RCE执行文件对比法1day分析0day验证
  • Web服务nginx实验1访问特定目录