
class Product { name: string constructor(name) { this.name = name } fn1() { console.log('prod') } fn2() { console.log('prod-2') }}// 工厂class Creator { create(name: string): Product { return new Product(name) }}// testconst creator = new Creator();const p1 = creator.create('p1');const p2 = creator.create('p2');const p3 = creator.create('p3');const p4 = creator.create('p4');

interface IProduct { name: string fn1: () => void fn2: () => void}class Product1 implements IProduct { name: string constructor(name: string) { this.name = name } fn1() {} fn2() {}}class Product2 implements IProduct { name: string constructor(name: string) { this.name = name } fn1() {} fn2() {}}class Creator { // 符合依赖倒置原则,我们返回的不是Product1或Product2,而是返回接口类型IProduct create(type: string, name: string): IProduct { // new 时的一些逻辑 if (type === 'p1') return new Product1(name) if (type === 'p2') return new Product2(name) throw new Error('Invalid type') }}// testconst creator = new Creator();const p1 = creator.create('p1', 'name1')const p11 = creator.create('p1', 'name11')const p2 = creator.create('p2', 'name2')
是否符合设计原则
- 工厂和类分离,解耦
- 可以扩展多个类(派生类,或平行的类)
- 工厂的创建逻辑也可以自由扩展