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

策略模式(及案例)

策略模式

1.策略接口

定义一组算法或操作的通用接口,通常是一个抽象类或接口。该接口声明了策略类所必须实现的方法。

示例:

class Strategy {doOperation() {}
}
2.具体策略

实现策略接口,提供具体的算法实现。每个具体策略类负责处理一种特定的情况或算法。它包含了实际的业务逻辑。

示例:

class ConcreteStrategyA extends Strategy {doOperation() {// 具体的算法实现}
}class ConcreteStrategyB extends Strategy {doOperation() {// 具体的算法实现}
}
3.上下文

维持一个对策略对象的引用,负责将客户端的请求委派给具体的策略。上下文通常会包含一个接口,使得客户端可以动态地切换策略。

示例:

class Context {constructor(strategy) {this.strategy = strategy;}setStrategy(strategy) {this.strategy = strategy;}executeStrategy() {this.strategy.doOperation();}
}
分数等级的案例:

假设我们有一个评分系统,根据用户的得分将其分为不同的等级。我们可以使用策略模式来实现这个例子,根据用户得分的不同区间采用不同的评级策略。以下是一个简单的JavaScript实现:

// 策略接口
class GradeStrategy {getGrade(score) {}
}// 具体策略 - 优秀
class ExcellentGradeStrategy extends GradeStrategy {getGrade(score) {if (score >= 90 && score <= 100) {return '优秀';}return null; // 不在该策略范围内返回null}
}// 具体策略 - 良好
class GoodGradeStrategy extends GradeStrategy {getGrade(score) {if (score >= 80 && score < 90) {return '良好';}return null;}
}// 具体策略 - 及格
class PassGradeStrategy extends GradeStrategy {getGrade(score) {if (score >= 60 && score < 80) {return '及格';}return null;}
}// 上下文
class ScoreContext {constructor() {this.strategies = [];}addStrategy(strategy) {this.strategies.push(strategy);}getGrade(score) {for (const strategy of this.strategies) {const grade = strategy.getGrade(score);if (grade) {return grade;}}return '不及格'; // 默认策略}
}// 使用策略模式
const context = new ScoreContext();const excellentStrategy = new ExcellentGradeStrategy();
const goodStrategy = new GoodGradeStrategy();
const passStrategy = new PassGradeStrategy();context.addStrategy(excellentStrategy);
context.addStrategy(goodStrategy);
context.addStrategy(passStrategy);console.log(context.getGrade(95)); // 输出: 优秀
console.log(context.getGrade(85)); // 输出: 良好
console.log(context.getGrade(70)); // 输出: 及格
console.log(context.getGrade(55)); // 输出: 不及格
http://www.lryc.cn/news/270270.html

相关文章:

  • 苹果CMS超级播放器专业版无授权全开源,附带安装教程
  • 项目记录:利用Redis实现缓存以提升查询效率
  • 腾讯云16核32G28M轻量服务器CPU流量性能测评
  • 【并发设计模式】聊聊等待唤醒机制的规范实现
  • CentOS:docker同一容器间通信
  • 数据治理:释放数据价值的关键
  • 新手快速上手掌握基础排序<一>
  • 2023年03月21日_chatgpt宕机事件的简单回顾
  • RK3568测试tdd
  • 机器学习系列13:通过随机森林获取特征重要性
  • flink中值得监控的几个指标
  • 最优化方法Python计算:无约束优化应用——逻辑分类模型
  • springboot定时执行某个任务
  • Java EE Servlet之Servlet API详解
  • neo4j运维管理
  • 【MYSQL】-函数
  • 传统船检已经过时?AR智慧船检来助力!!
  • JAVA进化史: JDK11特性及说明
  • 模型 安索夫矩阵
  • 性能手机新标杆,一加 Ace 3 发布会定档 1 月 4 日
  • Vue 框架前导:详解 Ajax
  • 3分钟快速安装 ClickHouse、配置服务、设置密码和远程登录以及修改数据目录
  • PHP8使用PDO对象增删改查MySql数据库
  • 证明:切线垂直于半径
  • 普中STM32-PZ6806L开发板(STM32CubeMX创建项目并点亮LED灯)
  • 【Windows】共享文件夹拍照还原防火墙设置(入站,出站设置)---图文并茂详细讲解
  • 1.决策树
  • 基于微信小程序的停车预约系统设计与实现
  • 再见2023,你好2024
  • 年度总结|存储随笔2023年度最受欢迎文章榜单TOP15-part1