js策略模式

定义一组算法,将每个算法封装成一个独立的类,并使它们可以互相替换。策略模式使得算法的变化不会影响到使用算法的客户。

js 复制代码
const priceProcessor = {

    pre(originPrice) {

      if (originPrice >= 100) {

        return originPrice - 20;

      }

      return originPrice * 0.9;

    },

    onSale(originPrice) {

      if (originPrice >= 100) {

        return originPrice - 30;

      }

      return originPrice * 0.8;

    },

    back(originPrice) {

      if (originPrice >= 200) {

        return originPrice - 50;

      }

      return originPrice;

    },

    fresh(originPrice) {

      return originPrice * 0.5;

    },

  };

  

  // 询价函数

function askPrice(tag, originPrice) {

    return priceProcessor[tag](originPrice)

  }
  
  
js 复制代码
// 定义策略接口

class Strategy {

  constructor() {

    if (this.constructor === Strategy) {

      throw new Error('不能实例化抽象类');

    }

  }

  // 定义算法方法

  algorithm() {

    throw new Error('必须实现 algorithm 方法');

  }

}

  

// 具体策略类 A

class ConcreteStrategyA extends Strategy {

  constructor() {

    super();

  }

  // 实现算法方法

  algorithm() {

    console.log('执行具体策略 A 的算法');

  }

}

  

// 具体策略类 B

class ConcreteStrategyB extends Strategy {

  constructor() {

    super();

  }

  // 实现算法方法

  algorithm() {

    console.log('执行具体策略 B 的算法');

  }

}

  

// 上下文类

class Context {

  constructor(strategy) {

    this.strategy = strategy;

  }

  // 执行算法方法

  executeAlgorithm() {

    this.strategy.algorithm();

  }

}

  

// 使用策略模式

let context = new Context(new ConcreteStrategyA());

context.executeAlgorithm();

  

context = new Context(new ConcreteStrategyB());

context.executeAlgorithm();
相关推荐
Q_Q5110082855 分钟前
python的婚纱影楼管理系统
开发语言·spring boot·python·django·flask·node.js·php
EutoCool17 分钟前
Qt窗口:菜单栏
开发语言·c++·嵌入式硬件·qt·前端框架
nightunderblackcat1 小时前
新手向:使用Python将多种图像格式统一转换为JPG
开发语言·python
我爱Jack1 小时前
深入解析 LinkedList
java·开发语言
engchina1 小时前
Python PDF处理库深度对比:PyMuPDF、pypdfium2、pdfplumber、pdfminer的关系与区别
开发语言·python·pdf
拓端研究室1 小时前
专题:2025供应链数智化与效率提升报告|附100+份报告PDF、原数据表汇总下载
开发语言·php
一百天成为python专家2 小时前
python库之jieba 库
开发语言·人工智能·python·深度学习·机器学习·pycharm·python3.11
Go Dgg2 小时前
【Go + Gin 实现「双 Token」管理员登录】
开发语言·golang·gin
十五年专注C++开发2 小时前
hiredis: 一个轻量级、高性能的 C 语言 Redis 客户端库
开发语言·数据库·c++·redis·缓存
WJ.Polar2 小时前
Python数据容器-集合set
开发语言·python