前端工程化 · 13/90
1. Babel 的工作原理 2. body-parser 中间件的作用 3. Babel 转译原理 4. 浏览器和 Node 中的事件循环区别 5. 职责链模式 6. 链模式 7. 命令模式 8. 组件封装设计 9. 数据统计 10. dependencies 和 devDependencies 的区别 11. CommonJS 和 ES6 模块引入的区别 12. 设计模式分类 13. 前端开发中常用的设计模式 14. 设计模式应用场景 15. 设计原则 16. 开发环境搭建要点 17. Electron 理解 18. 前后端分离是什么 19. 工厂模式 20. 前端代码重构 21. 前端组件化 22. 前端工程师职业发展 23. 前端工程化方向 24. 前端工程化的理解 25. 前端工程价值体现 26. 前端工程化 27. Git 常用命令与工作流 28. Gulp 任务自动化工具 29. 图片导出 30. 前端模块化规范 31. 迭代器模式 32. JavaScript 编码规范 33. 前端 CI/CD 流程 34. jQuery 生态对比 35. jQuery 实现原理 36. jQuery 与 Sizzle 选择器集成 37. Koa 中间件异常处理 38. jQuery 源码优秀实践 39. jQuery 与 Zepto 对比 40. jQuery UI 自定义组件 41. Koa 中间件不调用 await next() 的影响 42. Koa 在没有 async/await 时如何实现洋葱模型 43. Koa 和 Express 的区别 44. Koa 洋葱模型 45. 登录实现 46. 中介者模式 47. 模块模式 48. 小程序架构 49. 小程序常见问题 50. Monorepo 概念与工具 51. mpvue 框架 52. MVC vs MVP vs MVVM 53. Node.js ES Module 为什么必须加文件扩展名 54. MVC、MVP 和 MVVM 架构模式 55. Node.js 全局对象 56. Node.js 性能监控与优化 57. Node.js 多进程与进程通讯 58. Node.js 调试方法 59. Node.js 中的 process 对象 60. Node.js 的理解与应用场景 61. npm 是什么? 62. 观察者模式和发布订阅模式的区别 63. 页面重构方法 64. PM2 守护进程原理 65. 分页功能的前后端设计 66. PostCSS 作用 67. 项目管理方法 68. Rollup 打包工具 69. 高质量前端代码 70. JavaScript 单例模式实现 71. SSG 静态网站生成 72. 模板方法模式 73. 设计模式的六大原则 74. Tree Shaking 原理 75. 用户授权信息获取流程 76. Vite 原理与性能优势 77. Web App vs Hybrid App vs Native App 78. Web 前端开发注意事项 79. Web APP 设计原则 80. Webpack 构建流程 81. Hash vs ChunkHash vs ContentHash 82. Webpack 热更新原理 83. Webpack Loader 与 Plugin 区别 84. webpack 的 module、bundle、chunk 是什么 85. Webpack Proxy 工作原理与跨域解决 86. webpack、rollup、parcel 的选择 87. WePy 与 mpvue 对比 88. WXML 和 WXSS 89. Webpack Scope Hoisting 90. Zepto 实现原理

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

介绍前端开发中常用的 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 的响应式系统)
  • 装饰器模式用于动态扩展功能,避免子类爆炸
  • 根据实际需求选择设计模式,避免过度设计