推荐答案
策略模式(Strategy Pattern)是一种行为设计模式,它允许你定义一系列算法或行为,并将它们封装在独立的类中,使得它们可以相互替换。策略模式使得算法可以独立于使用它的客户端而变化。
适用场景
- 多种算法或行为:当你有多种算法或行为,且需要在运行时动态选择其中一种时。
- 避免条件语句:当你希望避免使用大量的条件语句来选择不同的算法或行为时。
- 扩展性:当你希望系统能够方便地扩展新的算法或行为,而不需要修改现有代码时。
本题详细解读
概念
策略模式通过将算法或行为封装在独立的类中,使得它们可以相互替换。客户端代码不需要知道具体的算法实现,只需要知道如何调用策略接口。这样,算法的变化不会影响到客户端代码。
作用
- 解耦:策略模式将算法的实现与使用它的客户端代码解耦,使得算法可以独立变化。
- 灵活性:客户端可以在运行时动态选择不同的策略,而不需要修改代码。
- 可维护性:由于算法被封装在独立的类中,添加新的算法或修改现有算法变得更加容易。
示例
假设我们有一个电商网站,需要根据不同的促销策略计算折扣。我们可以使用策略模式来实现:
// www.javascriptcn.com code example
// 策略接口
class DiscountStrategy {
applyDiscount(price) {
throw new Error("This method must be overridden");
}
}
// 具体策略类
class NoDiscount extends DiscountStrategy {
applyDiscount(price) {
return price;
}
}
class PercentageDiscount extends DiscountStrategy {
constructor(percentage) {
super();
this.percentage = percentage;
}
applyDiscount(price) {
return price * (1 - this.percentage / 100);
}
}
class FixedDiscount extends DiscountStrategy {
constructor(discount) {
super();
this.discount = discount;
}
applyDiscount(price) {
return price - this.discount;
}
}
// 上下文类
class ShoppingCart {
constructor(discountStrategy) {
this.discountStrategy = discountStrategy;
}
setDiscountStrategy(discountStrategy) {
this.discountStrategy = discountStrategy;
}
checkout(price) {
return this.discountStrategy.applyDiscount(price);
}
}
// 使用
const cart = new ShoppingCart(new NoDiscount());
console.log(cart.checkout(100)); // 100
cart.setDiscountStrategy(new PercentageDiscount(10));
console.log(cart.checkout(100)); // 90
cart.setDiscountStrategy(new FixedDiscount(20));
console.log(cart.checkout(100)); // 80在这个例子中,DiscountStrategy 是策略接口,NoDiscount、PercentageDiscount 和 FixedDiscount 是具体的策略类。ShoppingCart 是上下文类,它持有一个策略对象,并在 checkout 方法中调用策略的 applyDiscount 方法。通过这种方式,我们可以在运行时动态地改变折扣策略,而不需要修改 ShoppingCart 类的代码。
适用场景总结
- 多种算法或行为:如不同的折扣策略、支付方式等。
- 避免条件语句:如根据不同的条件选择不同的算法。
- 扩展性:如需要添加新的算法或行为时,只需添加新的策略类,而不需要修改现有代码。