UML - 图1

  1. class Product {
  2. name: string
  3. constructor(name) {
  4. this.name = name
  5. }
  6. fn1() {
  7. console.log('prod')
  8. }
  9. fn2() {
  10. console.log('prod-2')
  11. }
  12. }
  13. // 工厂
  14. class Creator {
  15. create(name: string): Product {
  16. return new Product(name)
  17. }
  18. }
  19. // test
  20. const creator = new Creator();
  21. const p1 = creator.create('p1');
  22. const p2 = creator.create('p2');
  23. const p3 = creator.create('p3');
  24. const p4 = creator.create('p4');

UML - 图2

  1. interface IProduct {
  2. name: string
  3. fn1: () => void
  4. fn2: () => void
  5. }
  6. class Product1 implements IProduct {
  7. name: string
  8. constructor(name: string) {
  9. this.name = name
  10. }
  11. fn1() {}
  12. fn2() {}
  13. }
  14. class Product2 implements IProduct {
  15. name: string
  16. constructor(name: string) {
  17. this.name = name
  18. }
  19. fn1() {}
  20. fn2() {}
  21. }
  22. class Creator {
  23. // 符合依赖倒置原则,我们返回的不是Product1或Product2,而是返回接口类型IProduct
  24. create(type: string, name: string): IProduct {
  25. // new 时的一些逻辑
  26. if (type === 'p1') return new Product1(name)
  27. if (type === 'p2') return new Product2(name)
  28. throw new Error('Invalid type')
  29. }
  30. }
  31. // test
  32. const creator = new Creator();
  33. const p1 = creator.create('p1', 'name1')
  34. const p11 = creator.create('p1', 'name11')
  35. const p2 = creator.create('p2', 'name2')

是否符合设计原则

  • 工厂和类分离,解耦
  • 可以扩展多个类(派生类,或平行的类)
  • 工厂的创建逻辑也可以自由扩展