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();
相关推荐
子豪-中国机器人4 分钟前
Python 阶段性综合强化训练(新版)
开发语言·python·语音识别
z落落6 分钟前
C# WinForm TreeView 树形控件+ListView控件+菜单栏
开发语言·c#
码云数智-园园6 分钟前
码云数智网站SEO设置指南:如何让百度搜索到你的网站
开发语言
赴生-6 分钟前
C++进阶 智能指针
开发语言·c++
wanger616 分钟前
Vue学习笔记
前端·javascript·vue.js
chao18984410 分钟前
GNSS软件接收机 MATLAB 实现(GPS L1 CA码)
开发语言·matlab
清水白石00813 分钟前
让对象像函数一样工作:深入理解 Python `__call__` 的作用与实战场景
开发语言·python
AI科技星34 分钟前
氢原子基态能级跃迁紫外频段光子频率计算
开发语言·网络·量子计算·agi·拓扑学
devilnumber40 分钟前
Java Lambda 表达式 200 条常见问题、坑点、易错点、规范清单
java·开发语言
大大杰哥44 分钟前
Vue2学习(3)--组件中的通信方式/组件之间的交互
java·前端·javascript