前端开发中常用的设计模式

介绍前端开发中常用的 6 种设计模式及其应用场景

问题

前端开发中常用哪些设计模式?

解答

设计模式是经过验证的面向对象软件开发最佳实践,提供了解决常见问题的可重用方案。

单例模式(Singleton)

确保一个类只有一个实例,并提供全局访问点。

class Singleton {
  constructor() {
    if (Singleton.instance) {
      return Singleton.instance;
    }
    Singleton.instance = this;
  }
  
  static getInstance() {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton();
    }
    return Singleton.instance;
  }
}

const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true

工厂模式(Factory)

通过工厂方法创建对象,隐藏具体实现,根据需要创建不同类型的对象。

class Button {
  render() {}
}

class IOSButton extends Button {
  render() {
    return '<button class="ios">iOS Button</button>';
  }
}

class AndroidButton extends Button {
  render() {
    return '<button class="android">Android Button</button>';
  }
}

class ButtonFactory {
  createButton(type) {
    switch(type) {
      case 'ios':
        return new IOSButton();
      case 'android':
        return new AndroidButton();
      default:
        throw new Error('Unknown button type');
    }
  }
}

const factory = new ButtonFactory();
const button = factory.createButton('ios');

观察者模式(Observer)

定义一对多的依赖关系,当对象状态改变时,所有依赖者都会收到通知并自动更新。

class Subject {
  constructor() {
    this.observers = [];
  }
  
  subscribe(observer) {
    this.observers.push(observer);
  }
  
  unsubscribe(observer) {
    this.observers = this.observers.filter(obs => obs !== observer);
  }
  
  notify(data) {
    this.observers.forEach(observer => observer.update(data));
  }
}

class Observer {
  update(data) {
    console.log('Received data:', data);
  }
}

const subject = new Subject();
const observer1 = new Observer();
subject.subscribe(observer1);
subject.notify('Hello'); // Received data: Hello

装饰器模式(Decorator)

动态地为对象添加新的行为,通过包装对象在运行时扩展功能。

class Coffee {
  cost() {
    return 5;
  }
}

class MilkDecorator {
  constructor(coffee) {
    this.coffee = coffee;
  }
  
  cost() {
    return this.coffee.cost() + 2;
  }
}

class SugarDecorator {
  constructor(coffee) {
    this.coffee = coffee;
  }
  
  cost() {
    return this.coffee.cost() + 1;
  }
}

let coffee = new Coffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
console.log(coffee.cost()); // 8

策略模式(Strategy)

定义一系列算法,将每个算法封装起来并使它们可以相互替换。

class PaymentStrategy {
  pay(amount) {}
}

class CreditCardStrategy extends PaymentStrategy {
  pay(amount) {
    console.log(`Paid ${amount} using Credit Card`);
  }
}

class PayPalStrategy extends PaymentStrategy {
  pay(amount) {
    console.log(`Paid ${amount} using PayPal`);
  }
}

class ShoppingCart {
  constructor(strategy) {
    this.strategy = strategy;
  }
  
  setStrategy(strategy) {
    this.strategy = strategy;
  }
  
  checkout(amount) {
    this.strategy.pay(amount);
  }
}

const cart = new ShoppingCart(new CreditCardStrategy());
cart.checkout(100); // Paid 100 using Credit Card
cart.setStrategy(new PayPalStrategy());
cart.checkout(200); // Paid 200 using PayPal

适配器模式(Adapter)

将一个类的接口转换成客户端期望的另一个接口,使接口不匹配的类可以协同工作。

class OldAPI {
  request() {
    return 'Old API data';
  }
}

class NewAPI {
  fetch() {
    return 'New API data';
  }
}

class APIAdapter {
  constructor(newAPI) {
    this.newAPI = newAPI;
  }
  
  request() {
    return this.newAPI.fetch();
  }
}

const oldAPI = new OldAPI();
const newAPI = new NewAPI();
const adapter = new APIAdapter(newAPI);

console.log(oldAPI.request()); // Old API data
console.log(adapter.request()); // New API data

关键点

  • 单例模式适用于全局状态管理、配置对象等场景
  • 工厂模式用于创建复杂对象,隐藏创建逻辑
  • 观察者模式常用于事件系统、数据绑定(如 Vue 的响应式系统)
  • 装饰器模式用于动态扩展功能,避免子类爆炸
  • 根据实际需求选择设计模式,避免过度设计