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();
相关推荐
swipe13 分钟前
把 JavaScript 原型讲透:从 `[[Prototype]]`、`prototype` 到 `constructor` 的完整心智模型
前端·javascript·面试
Dxy123931021634 分钟前
JS发送请求的方法详解
开发语言·javascript·ecmascript
sw1213891 小时前
C++中的代理模式实战
开发语言·c++·算法
難釋懷1 小时前
Lua语法入门-条件控制、函数
开发语言·junit·lua
桌面运维家1 小时前
Win10打印机共享故障排查:权限与网络配置详解
开发语言·网络·php
harrain1 小时前
antvG2折线图和区间range标记同时绘制
前端·javascript·vue.js·antv·g2
Sunshine for you2 小时前
实时操作系统中的C++
开发语言·c++·算法
史蒂芬_丁2 小时前
C++深度拷贝例子
java·开发语言·c++
Knight_AL2 小时前
Nacos 启动问题 Failed to create database ’D:\nacos\nacos\data\derby-data’
开发语言·数据库·python
leiming63 小时前
CAN 通信协议学习讲义(带图文 + C 语言代码)
c语言·开发语言·学习