11.策略模式
策略模式(Strategy Pattern)的主要目的是把一组可替换算法封装为独立策略对象,并在运行时按需切换
适合使用策略模式的场景
- 同一业务有多套计算规则(折扣、运费、风控等)
- 希望减少大量
if/else或switch分支 - 需要在运行时动态切换算法
- 希望新增策略时不修改已有核心流程
策略接口与具体策略
interface ShippingStrategy {
calc(weight: number): number;
}
class NormalShipping implements ShippingStrategy {
calc(weight: number): number {
return 8 + weight * 2;
}
}
class ExpressShipping implements ShippingStrategy {
calc(weight: number): number {
return 15 + weight * 3;
}
}
class FreeShipping implements ShippingStrategy {
calc(): number {
return 0;
}
}上下文类
class ShippingContext {
constructor(private strategy: ShippingStrategy) {}
setStrategy(strategy: ShippingStrategy): void {
this.strategy = strategy;
}
calc(weight: number): number {
return this.strategy.calc(weight);
}
}使用示例
const context = new ShippingContext(new NormalShipping());
console.log("普通运费:", context.calc(2));
context.setStrategy(new ExpressShipping());
console.log("加急运费:", context.calc(2));
context.setStrategy(new FreeShipping());
console.log("免运费:", context.calc(2));