JavaScript中可通过class的static方法模拟工厂模式,即用静态create/from等方法封装实例化逻辑,支持多态、配置驱动和依赖注入,实现创建与使用的解耦。

JavaScript 中 class 语法本身不直接提供“工厂方法”关键字,但可以通过在 class 内部定义静态方法(static method)来模拟工厂模式,实现灵活、可扩展的对象创建逻辑。
用 static 方法充当工厂方法
工厂方法的核心是:把对象的实例化过程封装起来,让调用方不直接使用 new MyClass(),而是通过一个命名清晰、带逻辑判断的方法来获取实例。
- 在 class 中声明
static create(...)或static from(...)等方法 - 方法内部根据参数决定构造哪种实例(可返回不同子类、预设配置对象,或做参数校验/转换)
- 返回 new 实例,或缓存后的实例(如单例变体),甚至返回 Promise(异步工厂)
示例:
class Button {
constructor(type, label, size = 'medium') {
this.type = type;
this.label = label;
this.size = size;
}
static createPrimary(label, size) {
return new Button('primary', label, size);
}
static createDanger(label) {
return new Button('danger', label, 'small');
}
static fromConfig(config) {
const { label, ...rest } = config;
return new Button('default', label, rest.size || 'medium');
}
}
// 使用
const btn1 = Button.createPrimary('提交');
const btn2 = Button.createDanger('删除');
const btn3 = Button.fromConfig({ label: '取消', size: 'large' });
结合继承实现多态工厂
当有多个子类时,可在父类中定义通用工厂接口,由子类覆盖实现,体现“工厂方法模式”的开闭原则。
- 父类声明
static create()为抽象占位(或抛错),子类重写 - 也可用一个统一工厂类,根据类型字符串分发到对应子类的静态创建方法
示例(统一工厂类):
在调试 Java 后端 API 故障时使用此技能,尤其适用于以下任务:分析日志、跨 Controller、Service 和 Mapper 层追踪请求、定位异常根因、检查 SQL 执行或参数流转,以及生成简洁的诊断结论与修复方案。
class Shape {}
class Circle extends Shape { constructor(radius) { super(); this.radius = radius; } }
class Rect extends Shape { constructor(width, height) { super(); this.width = width; this.height = height; } }
class ShapeFactory {
static create(type, ...args) {
switch (type.toLowerCase()) {
case 'circle': return new Circle(...args);
case 'rectangle': return new Rect(...args);
default: throw new Error(`Unknown shape: ${type}`);
}
}
}
const c = ShapeFactory.create('circle', 5);
const r = ShapeFactory.create('rectangle', 10, 20);
工厂方法 + 配置驱动(更实用的场景)
真实项目中,工厂常用于从 JSON 配置、用户行为或后端响应中动态生成 UI 组件、策略对象或服务实例。
- 工厂方法可做参数标准化(如把字符串 color 映射为 CSS 变量)
- 可注入依赖(如传入 eventBus、apiClient)
- 可返回代理对象、装饰后实例,或执行初始化副作用(如自动注册、日志上报)
示例(带依赖注入):
class Notification {
constructor(message, type, notifier) {
this.message = message;
this.type = type;
this.notifier = notifier;
}
show() {
this.notifier?.notify(this.message, this.type);
}
}
class NotificationFactory {
constructor(notifier) {
this.notifier = notifier;
}
createSuccess(msg) {
return new Notification(msg, 'success', this.notifier);
}
createError(msg) {
return new Notification(msg, 'error', this.notifier);
}
}
// 使用
const factory = new NotificationFactory(someToastService);
const success = factory.createSuccess('操作完成');
注意点与常见误区
虽然 class + static 方法很像传统 OOP 中的工厂方法,但 JavaScript 的灵活性也带来一些易忽略细节:
- static 方法无法被实例继承(即
instance.create()不行),只能通过类名调用 - 不要在工厂方法里过度耦合业务逻辑;保持职责单一:只负责“创建”,不负责“执行”
- 若需异步创建(如加载远程模板后再实例化组件),工厂方法应返回
Promise,并用async static - 避免用工厂方法替代构造函数的必要参数校验——两者可共存,工厂是更高层的封装
不复杂但容易忽略:工厂方法的价值不在语法,而在把“怎么造”和“造什么”解耦,让 class 更专注自身职责。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










