[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"$f8acizpc0swfs":3,"portal-md-433bf943294ba13641f3e0fcd6651fce":215},{"code":4,"data":5},2000,{"sectionUuid":6,"section":7,"prev":213,"next":214},"433bf943294ba13641f3e0fcd6651fce",{"uuid":6,"name":8,"category":9,"menu":10},"JavaScript设计模式","设计模式与Leetcode",[11,21,65,121,177],{"id":12,"isCategory":13,"label":14,"children":15,"access":20},4,true,"JavaScript设计模式教程",[16],{"id":17,"path":6,"label":18,"access":19},2,"JavaScript设计模式简介","free","vip",{"id":22,"isCategory":13,"label":23,"children":24,"access":20},17,"创建型模式",[25,29,33,37,41,45,49,53,57,61],{"id":26,"path":27,"label":28,"access":20},6,"86014c5756645a984a303cf904109a72","单例模式（Singleton）",{"id":30,"path":31,"label":32,"access":20},7,"e26bf57de21f374076623e77281208fe","单例模式实现方式（懒汉式、饿汉式、线程安全）",{"id":34,"path":35,"label":36,"access":20},8,"9f0c18c613a94794668a9005aa6a4c3c","工厂模式（Factory Method）",{"id":38,"path":39,"label":40,"access":20},9,"cb5dac646584074ef50c0acac7959507","工厂方法的实现与使用",{"id":42,"path":43,"label":44,"access":20},10,"d9de49755febd7c76a957c02cc40a89d","抽象工厂模式（Abstract Factory）",{"id":46,"path":47,"label":48,"access":20},11,"fc6c867917028eb0fd4bd7460ee65cf9","内置对象工厂",{"id":50,"path":51,"label":52,"access":20},12,"3c9f8000805e62871a2500057df0a47e","具体工厂的实现与示例",{"id":54,"path":55,"label":56,"access":20},13,"bb71a25d666a9c0f157e4cfe10dca134","Builder模式",{"id":58,"path":59,"label":60,"access":20},14,"c8579eef1d99493fc15032abab024d9b","使用Builder模式的优劣",{"id":62,"path":63,"label":64,"access":20},15,"93b3122786e31193fb1007363ad37606","原型模式（Prototype）",{"id":66,"isCategory":13,"label":67,"children":68,"access":20},33,"结构型模式",[69,73,77,81,85,89,93,97,101,105,109,113,117],{"id":70,"path":71,"label":72,"access":20},19,"ba15d718fda8cd3d26954532a24852a1","适配器模式（Adapter）",{"id":74,"path":75,"label":76,"access":20},20,"937f1d1f62b7a45281ae39e9284be5ca","类适配器与对象适配器的区别",{"id":78,"path":79,"label":80,"access":20},21,"3ad0ce5b1a8e46d54fc8bd7e73827bf0","桥接模式（Bridge）",{"id":82,"path":83,"label":84,"access":20},22,"6c144b5f283f2805307bbcefc59fd1c6","实现桥接模式的关键",{"id":86,"path":87,"label":88,"access":20},23,"a6b250e5e087757b7b3243b216176fc7","组合模式（Composite）",{"id":90,"path":91,"label":92,"access":20},24,"e39ee8553a206280597c132b55837ea6","组合模式的层次结构",{"id":94,"path":95,"label":96,"access":20},25,"e77f50c61d812f1200c70972f41312b9","装饰模式（Decorator）",{"id":98,"path":99,"label":100,"access":20},26,"6543e672ae7d8d4f118757015f46c15b","如何动态扩展对象的功能",{"id":102,"path":103,"label":104,"access":20},27,"e88e5fc29b7c3ebac6401178fa55903d","外观模式（Facade）",{"id":106,"path":107,"label":108,"access":20},28,"3c79139d1f5a4e022f9e22042a5222b3","简化系统与用户的交互",{"id":110,"path":111,"label":112,"access":20},29,"5bd46b841c05ba72f6548671e47c31c4","享元模式（Flyweight）",{"id":114,"path":115,"label":116,"access":20},30,"8ef9628a6f9005e4ee0f33606670ef7a","共享对象的实现",{"id":118,"path":119,"label":120,"access":20},31,"43556306e261da681414c638c1dc2df1","代理模式",{"id":122,"isCategory":13,"label":123,"children":124,"access":20},49,"行为型模式",[125,129,133,137,141,145,149,153,157,161,165,169,173],{"id":126,"path":127,"label":128,"access":20},35,"b0d437aec2c0584bd2a6c1b306b8da2f","中介者模式",{"id":130,"path":131,"label":132,"access":20},36,"f7b977367ca0c148374352bc0ee30e6d","观察者模式（Observer）",{"id":134,"path":135,"label":136,"access":20},37,"0762e1bb1045205f9d6c0263ea24b536","实现观察者模式的步骤",{"id":138,"path":139,"label":140,"access":20},38,"57a0c639d86f4302ecad1c8d3401a112","策略模式（Strategy）",{"id":142,"path":143,"label":144,"access":20},39,"7723d6673928a909faacb460476c4603","如何用策略模式实现动态行为",{"id":146,"path":147,"label":148,"access":20},40,"32325eebdc53e6a96377a425f9fa7835","迭代器模式（Iterator）",{"id":150,"path":151,"label":152,"access":20},41,"f17d91ab46365b9fd620a17d3f8524a8","命令模式（Command）",{"id":154,"path":155,"label":156,"access":20},42,"c40a99239ee239b392986fe3ad115654","解耦请求与处理的实现",{"id":158,"path":159,"label":160,"access":20},43,"6442991c218161c4a9f87d8e9fcdc952","状态模式（State）",{"id":162,"path":163,"label":164,"access":20},44,"6fbd3ce022df83fc0cba4a8855bfc4a1","状态转换与上下文的管理",{"id":166,"path":167,"label":168,"access":20},45,"a1057a3d22b9311c43957783b1f9871e","模板方法模式（Template Method）",{"id":170,"path":171,"label":172,"access":20},46,"7837f5a278e0eebe1cfb72bae4aa4f7d","责任链模式（Chain of Responsibility）",{"id":174,"path":175,"label":176,"access":20},47,"52ff9e045468f8bbe525a3815ee07237","处理请求的链式结构",{"id":178,"label":179,"children":180,"access":20},59,"其他",[181,185,189,193,197,201,205,209],{"id":182,"path":183,"label":184,"access":20},51,"6dc26317367577cad9c7a287d7db1fd7","业务代表模式",{"id":186,"path":187,"label":188,"access":20},52,"ac2c3fa8a11356a3b075d870153e0005","组合实体模式",{"id":190,"path":191,"label":192,"access":20},53,"8bb6e36b6db3711887619da9b7ce4c48","数据访问对象模式",{"id":194,"path":195,"label":196,"access":20},54,"2d17fb111cb466e830210c1f2ca47b00","前端控制器模式",{"id":198,"path":199,"label":200,"access":20},55,"b0e4eae0defd9070999346b19b23e3bf","服务定位器模式",{"id":202,"path":203,"label":204,"access":20},56,"bc4fa0a93f89b19c380764bf657be2f1","传输对象模式",{"id":206,"path":207,"label":208,"access":20},57,"01d55b31066a809c38a39fb406cbe993","深拷贝与浅拷贝的实现",{"id":210,"path":211,"label":212,"access":20},58,"9d81f920d1fd2f381afbb4ed568a1ca5","如何定义算法的骨架",null,{"path":27,"label":28,"access":20},{"code":4,"msg":216,"data":217},"success",{"last_modify_datetime":218,"sys_article_tags":219,"custom_article_tags":220,"special_column":221,"title":224,"id":225,"markdown":226,"number_of_visits":223,"next_page_url":27,"next_page_title":227,"last_page_url":225,"last_page_title":225,"category_path":228},"2026-07-26 23:40:07",[],[],{"name":222,"article_nums":223,"subscribe_nums":223},"公众号：CTO Plus",0,"JavaScript设计模式：提升代码质量与可维护性的关键","","\n## 什么是设计模式？\n\n设计模式是软件开发中针对常见问题的可重用解决方案，它们是在多年实践中总结出的最佳实践。如同建筑领域的蓝图，设计模式为开发者提供了经过验证的代码组织结构，帮助我们编写出更加灵活、可维护和可扩展的代码。\n\n在JavaScript中，设计模式尤为重要，因为JavaScript的灵活特性既提供了强大的表达能力，也可能导致代码结构混乱。恰当运用设计模式可以帮助我们扬长避短。\n\n## JavaScript中常用的设计模式\n\n### 1. 单例模式 (Singleton Pattern)\n\n单例模式确保一个类只有一个实例，并提供全局访问点。\n\n```javascript\nclass Singleton {\n  constructor() {\n    if (!Singleton.instance) {\n      Singleton.instance = this;\n    }\n    return Singleton.instance;\n  }\n  \n  \u002F\u002F 其他方法\n  someMethod() {\n    console.log('Do something');\n  }\n}\n\nconst instance1 = new Singleton();\nconst instance2 = new Singleton();\nconsole.log(instance1 === instance2); \u002F\u002F true\n```\n\n**应用场景**：全局状态管理、日志记录器、数据库连接等需要唯一实例的情况。\n\n### 2. 工厂模式 (Factory Pattern)\n\n工厂模式提供了一种创建对象的接口，而不需要指定具体类。\n\n```javascript\nclass Car {\n  constructor(options) {\n    this.type = options.type || 'standard';\n  }\n}\n\nclass Truck {\n  constructor(options) {\n    this.type = options.type || 'heavy';\n  }\n}\n\nclass VehicleFactory {\n  createVehicle(options) {\n    if (options.vehicleType === 'car') {\n      return new Car(options);\n    } else if (options.vehicleType === 'truck') {\n      return new Truck(options);\n    }\n  }\n}\n\nconst factory = new VehicleFactory();\nconst myCar = factory.createVehicle({ vehicleType: 'car' });\n```\n\n**应用场景**：需要根据不同条件创建不同类型对象的场景。\n\n### 3. 观察者模式 (Observer Pattern)\n\n观察者模式定义了一种一对多的依赖关系，当一个对象状态改变时，所有依赖它的对象都会得到通知。\n\n```javascript\nclass Subject {\n  constructor() {\n    this.observers = [];\n  }\n  \n  subscribe(observer) {\n    this.observers.push(observer);\n  }\n  \n  unsubscribe(observer) {\n    this.observers = this.observers.filter(obs => obs !== observer);\n  }\n  \n  notify(data) {\n    this.observers.forEach(observer => observer.update(data));\n  }\n}\n\nclass Observer {\n  update(data) {\n    console.log('Received data:', data);\n  }\n}\n\n\u002F\u002F 使用\nconst subject = new Subject();\nconst observer1 = new Observer();\nconst observer2 = new Observer();\n\nsubject.subscribe(observer1);\nsubject.subscribe(observer2);\nsubject.notify('Hello Observers!');\n```\n\n**应用场景**：事件处理系统、数据绑定、消息推送等。\n\n### 4. 模块模式 (Module Pattern)\n\n模块模式利用闭包封装私有变量和方法，只暴露公共接口。\n\n```javascript\nconst MyModule = (function() {\n  let privateVar = 'I am private';\n  \n  function privateMethod() {\n    console.log(privateVar);\n  }\n  \n  return {\n    publicMethod: function() {\n      privateMethod();\n    },\n    \n    setPrivateVar: function(value) {\n      privateVar = value;\n    }\n  };\n})();\n\nMyModule.publicMethod(); \u002F\u002F \"I am private\"\n```\n\n**应用场景**：组织代码、命名空间管理、信息隐藏。\n\n### 5. 装饰器模式 (Decorator Pattern)\n\n装饰器模式允许向现有对象添加新功能而不改变其结构。\n\n```javascript\nclass Coffee {\n  cost() {\n    return 5;\n  }\n}\n\n\u002F\u002F 装饰器\nfunction withMilk(coffee) {\n  const cost = coffee.cost();\n  coffee.cost = () => cost + 2;\n  return coffee;\n}\n\nfunction withSugar(coffee) {\n  const cost = coffee.cost();\n  coffee.cost = () => cost + 1;\n  return coffee;\n}\n\nlet myCoffee = new Coffee();\nmyCoffee = withMilk(myCoffee);\nmyCoffee = withSugar(myCoffee);\nconsole.log(myCoffee.cost()); \u002F\u002F 8\n```\n\n**应用场景**：动态添加功能、避免子类膨胀。\n\n## 如何选择合适的设计模式\n\n选择设计模式时，应考虑以下因素：\n\n1. **问题类型**：识别你正在解决的问题是否与某个模式的适用场景匹配\n2. **代码复杂度**：简单问题不需要复杂模式，避免过度设计\n3. **团队熟悉度**：选择团队成员熟悉的模式，或在引入新模式时提供适当培训\n4. **可维护性**：确保模式的使用真正提高了代码的可读性和可维护性\n\n## 结语\n\nJavaScript设计模式是每位开发者工具箱中不可或缺的部分。它们不仅提供了解决特定问题的方案，更重要的是培养了一种设计思维，帮助我们构建更加健壮和可扩展的应用程序。\n\n掌握设计模式需要时间和实践，建议从理解基本概念开始，逐步在实际项目中应用。记住，模式是指导而非约束，最终目标是编写出清晰、可维护的代码，而不是机械地套用模式。\n\n通过合理运用设计模式，我们可以充分发挥JavaScript的强大功能，同时避免其灵活性可能带来的混乱，创造出高质量的软件解决方案。\n\n\n","JavaScript 单例模式介绍","\u002Fdesign_pattern\u002Fjs"]