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)

  }
  
  
// 定义策略接口

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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值