设计模式

一、是什么

设计模式是针对特定问题场景的可复用解决方案,本质是对代码结构与职责的抽象。

前端常见设计模式:

  • 单例模式(Singleton)
  • 工厂模式(Factory)
  • 发布订阅模式(Pub/Sub)
  • 观察者模式(Observer)
  • 策略模式(Strategy)
  • 装饰器模式(Decorator)

二、为什么

随着项目复杂度提升,会出现:

  • 逻辑耦合严重
  • 可维护性差
  • 扩展困难

设计模式解决:

  • 解耦
  • 提升复用性
  • 提高可扩展性

三、核心原理

1. 单例模式

class Store {
  static instance;

  static getInstance() {
    if (!this.instance) {
      this.instance = new Store();
    }
    return this.instance;
  }
}

👉 应用:全局状态管理(Redux / Zustand)

2. 发布订阅模式

class EventBus {
  events = {};

  on(event, fn) {
    (this.events[event] ||= []).push(fn);
  }

  emit(event, data) {
    this.events[event]?.forEach((fn) => fn(data));
  }
}

👉 应用:

  • 跨组件通信
  • 微前端通信

3. 策略模式

const strategies = {
  A: () => console.log('A'),
  B: () => console.log('B'),
};

function execute(type) {
  strategies[type]();
}

👉 应用:

  • 表单校验
  • 支付方式选择

四、最佳实践

  • 优先使用组合而非继承
  • 模式 ≠ 滥用
  • 与业务结合(不要为了用而用)