定义一组算法,将每个算法封装成一个独立的类,并使它们可以互相替换。策略模式使得算法的变化不会影响到使用算法的客户。
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 方法');}}// 具体策略类 Aclass ConcreteStrategyA extends Strategy {constructor() {super();}// 实现算法方法algorithm() {console.log('执行具体策略 A 的算法');}}// 具体策略类 Bclass 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();