JavaScript工厂模式通过函数封装对象创建逻辑,依参数返回不同对象;可用字面量、构造函数或映射表实现;支持原型复用、动态扩展及类工厂进阶用法。
JavaScript 中的工厂模式通过一个函数(或方法)来封装对象创建逻辑,根据传入的参数动态返回不同结构或行为的对象实例,避免直接使用 new 多个构造函数,提升灵活性和可维护性。
最常见的方式是定义一个工厂函数,内部根据条件分支返回不同对象:
if/else 或 switch 判断类型标识(如字符串、配置项)示例:
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...
当对象需要共享方法或继承能力时,可让工厂函数返回由构造函数创建的实例:
Circle、Rectangle)new 实例化示例:
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, ...a
rgs) {
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 对象)示例:
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);
}
ES6+ 可结合 class 和静态方法模拟“类工厂”,返回定制化的类本身(而非实例):
new 实例化,更灵活示例(返回类):
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 级别输出