将一个复杂对象分解为多个简单对象来进行构建,将复杂构建层和表现层分离,是的相同的构建过程可以创建不同的表现的模式
建造者模式主要有4哥部分:product(产品类)、Builder(建造者类)、Director(指挥者类)、客户
- 客户提出需求
- 指挥者根据客户需求,指挥建造者去完成需求的各个部分
- 建造者完成相应的部分
产品类为一辆需要加工的空壳汽车
class Car {
constructor() {
this.carName = ''
this.number = ''
this.wheel = ''
this.engine = ''
}
}
建造者类里有负责各个部分的工人,可以看到每个工人负责的事项
class CarBuilder {
static nameBuilder(name) {
this.carName = name
}
static numberBuilder(number) {
this.number = number
}
static wheelBuilder(wheel) {
this.wheel = wheel
}
static engineBuilder(engine) {
this.engine = engine
}
static getCar(Car) {
const c = new Car()
c.carName = this.carName
c.number = this.number
c.wheel = this.wheel
c.engine = this.engine
return c
}
}
指挥者类,来指挥各个部分的工人以及他们的工作,他们各自的工作最终合并成一辆汽车
class Director {
action(carInfo) {
CarBuilder.nameBuilder(carInfo.name)
CarBuilder.numberBuilder(carInfo.number)
CarBuilder.wheelBuilder(carInfo.wheel)
CarBuilder.engineBuilder(carInfo.engine)
}
}
使用指挥者建造一辆汽车
const d = new Director()
d.action({
name: "红旗",
number:"京A88888",
wheel: "五星轮毂",
engine: "V12发动机"
})
const c = CarBuilder.getCar(Car)
console.log(c)
// {"carName":"红旗","number":"京A88888","wheel":"五星轮毂","engine":"V12发动机"}