策略模式(及案例)

策略模式

1.策略接口

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

示例:

js 复制代码
class Strategy {
  doOperation() {}
}
2.具体策略

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

示例:

js 复制代码
class ConcreteStrategyA extends Strategy {
  doOperation() {
    // 具体的算法实现
  }
}

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

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

示例:

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

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

js 复制代码
// 策略接口
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)); // 输出: 不及格
相关推荐
意法半导体STM3211 小时前
【官方原创】如何为STM32CubeMX2配置Visual Studio Code配置方案
vscode·stm32·单片机·嵌入式硬件·策略模式·stm32cubemx·嵌入式开发
山东点狮信息科技有限公司1 天前
企业级 MES 制造执行系统架构设计与实践
spring cloud·性能优化·系统架构·策略模式·点狮
zzqssliu1 天前
基于策略模式与责任链的代购商品多源采集架构实战
架构·策略模式
mxpan2 天前
macOS 13+ 上使用 macFUSE + NTFS-3G 读写 NTFS 移动硬盘技术说明
macos·策略模式
折哥的程序人生 · 物流技术专研3 天前
Java 23 种设计模式:从踩坑到精通 | 番外:编排器+策略模式在多平台电子面单中的实战(含性能压测)
设计模式·策略模式·代码重构·java设计模式·编排器·电子面单·从踩坑到精通
忧云3 天前
2026年最新 Cursor 国内使用 DeepSeek API等各模型使用完整教程
ai编程·策略模式·cursor·byok·cursor使用国内大模型
AIex-YH3 天前
三域贯通11/12:生物制造的“死亡之谷“,CDMO 是桥还是船?
运维·制造·策略模式
回忆2012初秋4 天前
【Nginx】原理、配置与运维实战(2)
运维·nginx·策略模式
怎么没有名字注册了啊4 天前
macOS 基于 CSDN GitCode + Homebrew Tap 发布 Qt .app 二进制程序通用教程(homebrew 安装自己的软件)
策略模式·homebrew·formula·ruhy
坏小虎5 天前
macOS 安装 Ghostty 终端完整教程:环境、依赖与美化配置
macos·策略模式