信息发布→ 登录 注册 退出

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

发布时间:2025-12-24

点击量:
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');
  }
}

const circle = createShape('circle', { radius: 5 }); console.log(circle.area()); // 78.5398...

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

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

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

示例:

class Circle {
  constructor(radius) {
    this.radius = radius;
  }
  area() { return Math.PI * this.radius ** 2; }
}

class Rectangle { constructor(width, height) { this.width = width; this.height = height; } area() { return this.width * this.height; } }

function createShape(type, ...args) { switch (type) { case 'circle': return new Circle(...args); case 'rectangle': return new Rectangle(...args); default: throw new Error('Unsupported type'); } }

const rect = createShape('rectangle', 4, 6); console.log(rect instanceof Rectangle); // true

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

当类型较多时,用配置对象代替 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; }
  })
};

function createShape(type, ...args) { const creator = creators[type]; if (!creator) throw new Error(No creator for ${type}); return creator(...args); }

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

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

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

示例(返回类):

function createLogger(level = 'info') {
  return class Logger {
    log(msg) {
      console[level](`[${new Date().toISOString()}] ${msg}`);
    }
  };
}

const InfoLogger = createLogger('info'); const DebugLogger = createLogger('debug');

const logger1 = new InfoLogger(); logger1.log('Hello'); // info 级别输出

标签:# javascript  # es6  # java  # 编码  # proxy  # switch  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!