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();
相关推荐
海盗12341 分钟前
WPF上位机组件开发-设备状态运行图基础版
开发语言·c#·wpf
看我干嘛!3 分钟前
python第四次作业
开发语言·python
Coder_preston3 分钟前
Java集合框架详解
java·开发语言
多多*7 分钟前
2026年最新 测试开发工程师相关 Linux相关知识点
java·开发语言·javascript·算法·spring·java-ee·maven
会编程的土豆16 分钟前
简易植物大战僵尸游戏 JavaScript版之html
javascript·游戏·html
雯0609~18 分钟前
hiprint-官网vue完整版本+实现客户端配置+可实现直接打印(在html版本增加了条形码、二维码拖拽等)
前端·javascript·vue.js
VT.馒头19 分钟前
【力扣】2705. 精简对象
javascript·数据结构·算法·leetcode·职场和发展·typescript
摘星编程24 分钟前
在OpenHarmony上用React Native:Switch禁用状态
javascript·react native·react.js
2301_7634725832 分钟前
实时系统下的C++编程
开发语言·c++·算法
阿猿收手吧!39 分钟前
【C++】深入理解C++ Atomic内存序:解决什么问题?怎么用?
开发语言·c++