es6 语法学习 - 策略模式

es6 语法学习 - 策略模式

一、基本概念

策略设计模式(Strategy Pattern)是一种行为设计模式,它定义了一系列算法,并将每个算法封装在一个单独的类中,使得这些算法可以相互替换。策略模式的核心思想是将算法与主对象分开,允许对象在运行时动态地选择不同的算法或行为。

二、 优点

  • 提高代码灵活性:将对象的行为封装到不同的策略中,代码变得更加灵活且更易于修改。
  • 增强代码可重用性:封装代码在不同项目中重复使用。
  • 支持开闭原则:策略模式允许在不修改原有系统的基础上,增加新的行为或算法。
  • 简化测试:通过将算法和行为将对象分离,有助于测试。

三、缺点

  • 增加系统复杂性:随着策略类的增多,系统可能会变得复杂,增加了维护的难度。
  • 客户端心智负担:客户端需要了解所有的策略类,并自行决定使用哪个策略类,这可能会增加客户端的负担。

四、使用场景

  • 当需要在不同情况下使用不同的算法或行为时。
  • 当一个类有多种行为或算法,并且这些行为或算法可以在运行时切换时。
  • 当需要避免使用多重条件语句或大量的 if-else 语句时。

五、示例代码

以下是一个使用 ES6 语法的 JavaScript 示例,展示了策略模式的应用。假设我们有一个简单的电子商务系统,用户可以选择不同的折扣策略来计算订单的最终价格。

// 定义一个策略接口
class DiscountStrategy {
  calculate(order) {
    throw new Error('Subclasses must implement abstract method');
  }
}

// 具体的策略类:无折扣策略
class NoDiscountStrategy extends DiscountStrategy {
  calculate(order) {
    return order.getTotalPrice();
  }
}

// 具体的策略类:百分比折扣策略
class PercentageDiscountStrategy extends DiscountStrategy {
  constructor(percentage) {
    super();
    this.percentage = percentage;
  }

  calculate(order) {
    const discount = order.getTotalPrice() * (this.percentage / 100);
    return order.getTotalPrice() - discount;
  }
}

// 具体的策略类:固定金额折扣策略
class FixedAmountDiscountStrategy extends DiscountStrategy {
  constructor(amount) {
    super();
    this.amount = amount;
  }

  calculate(order) {
    return order.getTotalPrice() - this.amount;
  }
}

// 订单类
class Order {
  constructor(items) {
    this.items = items; // 假设items是一个包含每个商品价格和数量的数组
  }

  getTotalPrice() {
    // 计算订单的总价格(这里简单处理为所有商品价格之和)
    return this.items.reduce(
      (total, item) => total + item.price * item.quantity,
      0
    );
  }

  // 设置折扣策略
  setDiscountStrategy(strategy) {
    this.strategy = strategy;
  }

  // 计算最终价格
  getFinalPrice() {
    return this.strategy.calculate(this);
  }
}

// 使用策略模式
const items = [
  { price: 100, quantity: 2 },
  { price: 50, quantity: 1 },
];

const order = new Order(items);

// 使用无折扣策略
order.setDiscountStrategy(new NoDiscountStrategy());
console.log('No Discount Final Price:', order.getFinalPrice()); // 输出:250

// 使用百分比折扣策略(10%折扣)
order.setDiscountStrategy(new PercentageDiscountStrategy(10));
console.log('Percentage Discount Final Price:', order.getFinalPrice()); // 输出:225

// 使用固定金额折扣策略(50元折扣)
order.setDiscountStrategy(new FixedAmountDiscountStrategy(50));
console.log('Fixed Amount Discount Final Price:', order.getFinalPrice()); // 输出:200

策略模式使得算法可以独立于使用它的客户端而变化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值