Skip to content

策略模式

行为型模式

特点

策略模式的核心在于定义一系列算法,并将每个算法封装起来,使它们可以互相替换。

  • 适用于多种条件分支
  • 避免使用大量的 if...else 或 switch...case 语句
  • 每个分支单独处理,相互隔离

使用场景

策略模式适用于需要动态切换算法或行为的场景,如支付方式选择、折扣策略等。

普通写法

ts
class User {
  type: string;

  constructor(type: string) {
    this.type = type;
  }
  buy() {
    const { type } = this;
    if (type === 'vip') {
      console.log('VIP用户');
    }
    if (type === 'normal') {
      console.log('普通用户');
    }
    if (type === '') {
      console.log('未知用户');
    }
  }
}

策略模式

ts
interface IUser {
  buy: () => void;
}

class VipUser implements IUser {
  buy(): void {
    console.log('VIP用户');
  }
}

class NormalUser implements IUser {
  buy(): void {
    console.log('普通用户');
  }
}

const vipUser = new VipUser();
const normalUser = new NormalUser();

基于 MIT 许可发布