介绍
创建对象的一种方式。不用每次都亲自创建对象,而是通过一个既定的“工厂”来生产对象。
示例
- 去购买奶茶,直接点餐、取餐、不会自己亲手做
- 商店要“封装”做奶茶的工作,做好直接给你
UML类图
代码
interface IProduct {
name: string
fn1: () => void
fn2: () => void
}
class Product1 implements IProduct {
name: string
constructor(name: string) {
this.name = name
}
fn1() {
alert('product1 fn1')
}
fn2() {
alert('product1 fn2')
}
}
class Product2 implements IProduct {
name: string
constructor(name: string) {
this.name = name
}
fn1() {
alert('product2 fn1')
}
fn2() {
alert('product2 fn2')
}
}
class Creator {
// 依赖倒置原则
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')
}
}
// test
const creator = new Creator()
const p1 = creator.create('p1', 'name1')
const p11 = creator.create('p1', 'name11')
const p2 = creator.create('p2', 'name2')
const p21 = creator.create('p2', 'name21')
使用场景
- Jquery --$
- VUe_createElementVNode
- React createElement
设计原则验证:
- 构造函数和创建者分离
- 符合开放封闭原则
注意事项
遇到 new class 的地方,就要考虑工厂模式