登录
首页 >  文章 >  前端

JavaScript工厂模式详解与动态创建方法

时间:2025-12-31 17:36:42 226浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《JavaScript工厂模式实现与动态对象创建》,正文内容主要涉及到等等,如果你正在学习文章,或者是对文章有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

JavaScript工厂模式通过函数封装对象创建逻辑,依参数返回不同对象;可用字面量、构造函数或映射表实现;支持原型复用、动态扩展及类工厂进阶用法。

JavaScript如何实现工厂模式_JavaScript如何动态创建不同类型对象

JavaScript 中的工厂模式通过一个函数(或方法)来封装对象创建逻辑,根据传入的参数动态返回不同结构或行为的对象实例,避免直接使用 new 多个构造函数,提升灵活性和可维护性。

用函数实现基础工厂模式

最常见的方式是定义一个工厂函数,内部根据条件分支返回不同对象:

  • if/elseswitch 判断类型标识(如字符串、配置项)
  • 每个分支返回一个具有特定属性和方法的对象字面量,或调用对应构造函数
  • 不暴露具体类,使用者只关心输入和输出,解耦创建过程

示例:

function createShape(type, options) {
  switch (type) {
    case 'circle':
      return {
        type: 'circle',
        radius: options.radius || 1,
        area() { return Math.PI * this.radius ** 2; }
      };
    case 'rectangle':
      return {
        type: 'rectangle',
        width: options.width || 1,
        height: options.height || 1,
        area() { return this.width * this.height; }
      };
    default:
      throw new Error('Unknown shape type');
  }
}
<p>const circle = createShape('circle', { radius: 5 });
console.log(circle.area()); // 78.5398...
</p>

结合构造函数与原型增强复用性

当对象需要共享方法或继承能力时,可让工厂函数返回由构造函数创建的实例:

  • 预先定义多个构造函数(如 CircleRectangle
  • 工厂函数内根据类型选择并调用对应构造函数,用 new 实例化
  • 方法定义在原型上,节省内存,支持 instanceof 检测

示例:

class Circle {
  constructor(radius) {
    this.radius = radius;
  }
  area() { return Math.PI * this.radius ** 2; }
}
<p>class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() { return this.width * this.height; }
}</p><p>function createShape(type, ...args) {
switch (type) {
case 'circle': return new Circle(...args);
case 'rectangle': return new Rectangle(...args);
default: throw new Error('Unsupported type');
}
}</p><p>const rect = createShape('rectangle', 4, 6);
console.log(rect instanceof Rectangle); // true
</p>

用对象映射替代硬编码分支

当类型较多时,用配置对象代替 switch,更易扩展和测试:

  • 将构造函数或创建函数注册到一个映射表中(如 creators 对象)
  • 工厂函数查表调用,新增类型只需添加映射项,无需改主逻辑
  • 支持异步创建(如动态 import)、缓存、校验等增强逻辑

示例:

const creators = {
  circle: (radius) => new Circle(radius),
  rectangle: (w, h) => new Rectangle(w, h),
  triangle: (base, height) => ({
    type: 'triangle',
    base,
    height,
    area() { return 0.5 * this.base * this.height; }
  })
};
<p>function createShape(type, ...args) {
const creator = creators[type];
if (!creator) throw new Error(<code>No creator for ${type}</code>);
return creator(...args);
}
</p>

工厂模式与类工厂(Class Factory)进阶用法

ES6+ 可结合 class 和静态方法模拟“类工厂”,返回定制化的类本身(而非实例):

  • 适用于需要生成不同行为策略类、带默认配置的子类等场景
  • 返回的是类(函数),调用者再用 new 实例化,更灵活
  • 配合 Proxy 或装饰器可进一步注入行为

示例(返回类):

function createLogger(level = 'info') {
  return class Logger {
    log(msg) {
      console[level](`[${new Date().toISOString()}] ${msg}`);
    }
  };
}
<p>const InfoLogger = createLogger('info');
const DebugLogger = createLogger('debug');</p><p>const logger1 = new InfoLogger();
logger1.log('Hello'); // info 级别输出
</p>

今天带大家了解了的相关知识,希望对你有所帮助;关于文章的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>