js实现工厂
工厂模式的概念
工厂模式是一种创建型设计模式,用于封装对象的创建逻辑,避免直接在代码中通过 new 实例化对象。它通过工厂方法或工厂类统一管理对象的创建过程,提高代码的可维护性和扩展性。
简单工厂模式
通过一个工厂函数集中创建对象,根据传入的参数返回不同的实例。

function createProduct(type) {
switch (type) {
case 'A':
return new ProductA();
case 'B':
return new ProductB();
default:
throw new Error('Unknown product type');
}
}
class ProductA {
operate() {
return 'Product A';
}
}
class ProductB {
operate() {
return 'Product B';
}
}
// 使用
const product = createProduct('A');
console.log(product.operate()); // 输出: Product A
工厂方法模式
将对象的创建延迟到子类,通过继承实现不同产品的工厂。
class Factory {
createProduct() {
throw new Error('Method must be implemented');
}
}
class ProductAFactory extends Factory {
createProduct() {
return new ProductA();
}
}
class ProductBFactory extends Factory {
createProduct() {
return new ProductB();
}
}
// 使用
const factoryA = new ProductAFactory();
const productA = factoryA.createProduct();
console.log(productA.operate()); // 输出: Product A
抽象工厂模式
提供一个接口用于创建相关或依赖对象的家族,而不需要指定具体类。

class AbstractFactory {
createProductA() {
throw new Error('Method must be implemented');
}
createProductB() {
throw new Error('Method must be implemented');
}
}
class ConcreteFactory1 extends AbstractFactory {
createProductA() {
return new ProductA1();
}
createProductB() {
return new ProductB1();
}
}
class ProductA1 {
operate() {
return 'Product A1';
}
}
class ProductB1 {
operate() {
return 'Product B1';
}
}
// 使用
const factory1 = new ConcreteFactory1();
const productA1 = factory1.createProductA();
console.log(productA1.operate()); // 输出: Product A1
适用场景
- 需要动态创建不同类的实例时。
- 对象创建逻辑复杂或需要统一管理时。
- 希望解耦对象的使用和创建过程时。
优缺点
优点:
- 代码更清晰,避免重复的
new操作。 - 易于扩展新的产品类型。
缺点:
- 引入额外的工厂类可能增加代码复杂度。






