如何在TypeScript中实现工厂模式?

解读

该问题考察候选人对TypeScript类型系统与设计模式结合的理解能力。工厂模式作为面向对象编程的核心设计模式之一,在TypeScript中需要通过类型注解、泛型和接口等特性实现类型安全的多态对象创建。面试场景中,候选人需展示对类型系统增强代码健壮性的认知,以及如何在实际开发中应用工厂模式解决复杂对象实例化问题。

知识点

  1. 类型注解与类型推断的结合应用
  2. 接口定义统一的产品规范
  3. 泛型实现灵活的工厂函数
  4. 类型守卫确保分支逻辑类型安全
  5. 模块化封装工厂逻辑
  6. 类型断言处理潜在类型兼容问题
  7. 工厂模式与依赖注入的协同使用

答案

在TypeScript中实现工厂模式需遵循类型安全原则,核心实现方式如下:

// 1. 定义产品接口
interface Product {
  id: string;
  name: string;
  getType(): string;
}

// 2. 具体产品类实现接口
class ConcreteProductA implements Product {
  getType(): string {
    return 'A';
  }
}

class ConcreteProductB implements Product {
  getType(): string {
    return 'B';
  }
}

// 3. 工厂函数实现类型安全创建
function createProduct(type: 'A' | 'B'): Product {
  switch (type) {
    case 'A':
      return new ConcreteProductA();
    case 'B':
      return new ConcreteProductB();
    default:
      throw new Error(`Unknown product type: ${type}`);
  }
}

// 4. 泛型增强工厂灵活性
function createProduct<T extends Product>(type: 'A' | 'B'): T {
  if (type === 'A') {
    return <T>new ConcreteProductA(); // 类型断言
  } else {
    return <T>new ConcreteProductB(); // 类型断言
  }
}

// 5. 类型守卫优化分支逻辑
function isProductA(product: Product): product is ConcreteProductA {
  return (product as ConcreteProductA).getType() === 'A';
}

function createProductWithGuard(productType: 'A' | 'B'): Product {
  const product = productType === 'A' 
    ? new ConcreteProductA() 
    : new ConcreteProductB();
  
  if (isProductA(product)) {
    // 安全地调用A特有的方法
  }
  
  return product;
}

拓展思考

  1. 类型参数化:可将工厂函数改为泛型形式,通过new (...args: any[]) => T实现构造函数参数的类型校验,例如:
function createProduct<T extends new (...args: any[]) => Product>(constructor: T, ...args: any[]): InstanceType<T> {
  return new constructor(...args);
}
  1. 动态工厂模式:结合TypeScript的映射类型实现运行时工厂,需注意类型断言的使用边界:
type ProductType = 'A' | 'B';
type ProductConstructors = {
  [K in ProductType]: new () => Product;
};

const productFactories: ProductConstructors = {
  A: ConcreteProductA,
  B: ConcreteProductB
};

function createProductDynamic(type: ProductType): Product {
  return new productFactories[type]();
}
  1. 框架集成场景:在React中使用工厂模式创建组件时,需注意TypeScript的组件类型校验机制,例如通过React.ComponentType进行类型标注。

  2. 编译器配置:在tsconfig.json中启用strict模式时,工厂模式的类型校验会更严格,需确保所有分支都包含类型返回声明,避免隐式any类型风险。

  3. 工厂模式变体:可结合抽象类实现工厂模式,通过abstract class ProductBase定义公共方法,具体产品类继承该抽象类,工厂函数通过类型守卫区分实例类型。