定义

定义一个创建对象的类,由这个类来封装实例化对象的行为

优缺点

优点
客户类与具体子类解耦;客户类不需要知道所有子类细节
缺点
工厂类职责过重;增加工厂类增加了系统的复杂度;系统扩展困难(会修改工厂逻辑)

应用场景

工厂类负责创建的对象较少、客户端对如何创建对象不关心

角色

SimpleFactory:简单工厂类
Product:抽象产品类
ConcreteProduct:具体产品类

类图

image.png

代码

  1. // 抽象产品接口
  2. interface Product{}
  3. // 具体产品一
  4. class ConcreteProduct1 implements Product {
  5. constructor(){}
  6. }
  7. // 具体产品二
  8. class ConcreteProduct2 implements Product {
  9. constructor(){}
  10. }
  11. // 简单工厂
  12. class SimpleFactory {
  13. public static createProduct(type : number) : Product {
  14. let product = null;
  15. if (type === 1) {
  16. product = new ConcreteProduct1();
  17. } else if ( type === 2) {
  18. product = new ConcreteProduct2();
  19. }
  20. return product;
  21. }
  22. }
  23. // 使用
  24. let product = SimpleFactory.createProduct(1);
  25. console.log(product);