js实现工厂
工厂模式概述
工厂模式是一种创建型设计模式,用于封装对象的创建过程,使代码更灵活、可维护。JavaScript中可通过函数或类实现工厂模式,根据输入参数返回不同对象实例。
简单工厂实现
通过函数返回不同对象实例:
function createProduct(type) {
switch(type) {
case 'A':
return { name: 'Product A', price: 100 };
case 'B':
return { name: 'Product B', price: 200 };
default:
throw new Error('Unknown product type');
}
}
const productA = createProduct('A');
const productB = createProduct('B');
工厂方法模式
通过子类决定实例化哪个类:
class ProductFactory {
createProduct() {
throw new Error('Method must be implemented');
}
}
class ProductAFactory extends ProductFactory {
createProduct() {
return { name: 'Product A', price: 100 };
}
}
class ProductBFactory extends ProductFactory {
createProduct() {
return { name: 'Product B', price: 200 };
}
}
const factoryA = new ProductAFactory();
const productA = factoryA.createProduct();
抽象工厂模式
创建相关或依赖对象的家族:
class UIFactory {
createButton() {
throw new Error('Method must be implemented');
}
createDialog() {
throw new Error('Method must be implemented');
}
}
class MacFactory extends UIFactory {
createButton() {
return { render: () => 'Mac button' };
}
createDialog() {
return { show: () => 'Mac dialog' };
}
}
class WinFactory extends UIFactory {
createButton() {
return { render: () => 'Windows button' };
}
createDialog() {
return { show: () => 'Windows dialog' };
}
}
const macFactory = new MacFactory();
const macButton = macFactory.createButton();
使用场景
- 需要创建多种类似对象
- 对象创建过程复杂
- 需要解耦对象创建和使用
- 需要根据不同环境创建不同对象
优缺点分析
优点:
- 封装创建逻辑
- 代码可扩展性强
- 符合单一职责原则
- 便于单元测试
缺点:

- 可能增加代码复杂度
- 需要创建更多类/函数
- 对简单对象创建可能过度设计






