跳到主要内容

策略模式(Strategy Pattern)

策略模式(Strategy Pattern)是一种行为型设计模式,它定义了一系列算法,将每个算法封装成一个独立的策略对象,并使这些策略对象可以互相替换。策略模式允许客户端选择要使用的算法,而不必更改其使用算法的代码。这种模式有助于减少算法与客户端之间的耦合度,并提供了更大的灵活性。

策略模式的核心思想是将不同的算法封装成独立的策略类,这些策略类都实现了相同的接口或抽象类。客户端通过使用策略对象来选择所需的算法,而不必知道算法的实现细节。

场景

替代条件分支:策略模式可以替代大量的条件分支语句,使代码更加清晰和易于维护。

动态切换算法:策略模式允许在运行时选择不同的算法,从而实现动态切换和配置。

共享算法实现:多个对象需要使用相同的算法,策略模式可以避免代码重复。

避免继承的复杂性:策略模式可以用来避免类继承的复杂性,因为不同的算法可以作为独立的策略类存在。

实现

// 折扣策略接口
class DiscountStrategy {
applyDiscount(price) {
throw new Error("applyDiscount method must be overridden");
}
}

// 具体折扣策略类
class NoDiscount extends DiscountStrategy {
applyDiscount(price) {
return price;
}
}

class TenPercentDiscount extends DiscountStrategy {
applyDiscount(price) {
return price - price * 0.1;
}
}

class TwentyPercentDiscount extends DiscountStrategy {
applyDiscount(price) {
return price - price * 0.2;
}
}

// 上下文,用于设置和应用折扣策略
class ShoppingCart {
constructor(discountStrategy) {
this.discountStrategy = discountStrategy;
this.items = [];
}

addItem(item) {
this.items.push(item);
}

calculateTotal() {
const subtotal = this.items.reduce((total, item) => total + item.price, 0);
return this.discountStrategy.applyDiscount(subtotal);
}
}

// 客户端代码
const noDiscount = new NoDiscount();
const tenPercentDiscount = new TenPercentDiscount();
const twentyPercentDiscount = new TwentyPercentDiscount();

const cart1 = new ShoppingCart(noDiscount);
cart1.addItem({ name: "Item 1", price: 50 });
cart1.addItem({ name: "Item 2", price: 30 });
console.log("Total (No Discount):", cart1.calculateTotal());

const cart2 = new ShoppingCart(tenPercentDiscount);
cart2.addItem({ name: "Item 1", price: 50 });
cart2.addItem({ name: "Item 2", price: 30 });
console.log("Total (10% Discount):", cart2.calculateTotal());

const cart3 = new ShoppingCart(twentyPercentDiscount);
cart3.addItem({ name: "Item 1", price: 50 });
cart3.addItem({ name: "Item 2", price: 30 });
console.log("Total (20% Discount):", cart3.calculateTotal());

在上面的示例中,DiscountStrategy 是折扣策略接口,它包含一个 applyDiscount 方法。具体的折扣策略类如 NoDiscount、TenPercentDiscount 和 TwentyPercentDiscount 都实现了这个接口。

ShoppingCart 是上下文类,它接受一个折扣策略作为参数,并通过该策略来计算购物车中商品的总价。

客户端代码可以选择不同的折扣策略,从而获得不同的总价。这种方式下,客户端代码与具体折扣策略的实现相分离,使得系统更加灵活,可以轻松添加新的折扣策略。策略模式是一个非常有用的模式,特别适用于需要灵活处理多个算法或策略的场景。