建造者模式又称为生成期末数分布构建一个复杂对象,讲一个复杂的构建曾与其表示层分离
在工厂模式中构建的是完整的个体,而且不关心构建的过程,只需要了解构建结果
建造者模式:
// 建造者,汽车部件厂家,提供具体零部件的生产
function CarBuilder({ color = 'white', weight = 0 }) {
this.color = color
this.weight = weight
}
// 生产部件,轮胎
CarBuilder.prototype.buildTyre = function(type) {
switch (type) {
case 'small':
this.tyreType = '小号轮胎'
this.tyreIntro = '正在使用小号轮胎'
break
case 'normal':
this.tyreType = '中号轮胎'
this.tyreIntro = '正在使用中号轮胎'
break
case 'big':
this.tyreType = '大号轮胎'
this.tyreIntro = '正在使用大号轮胎'
break
}
}
// 生产部件,发动机
CarBuilder.prototype.buildEngine = function(type) {
switch (type) {
case 'small':
this.engineType = '小马力发动机'
this.engineIntro = '正在使用小马力发动机'
break
case 'normal':
this.engineType = '中马力发动机'
this.engineIntro = '正在使用中马力发动机'
break
case 'big':
this.engineType = '大马力发动机'
this.engineIntro = '正在使用大马力发动机'
break
}
}
/* 奔驰厂家,负责最终汽车产品的装配 */
function benChiDirector(tyre, engine, param) {
var _car = new CarBuilder(param)
_car.buildTyre(tyre)
_car.buildEngine(engine)
return _car
}
// 获得产品实例
var benchi1 = benChiDirector('small', 'big', { color: 'red', weight: '1600kg' })
console.log(benchi1)
// 输出:
// {
// color: "red"
// weight: "1600kg"
// tyre: Tyre {tyreType: "小号轮胎", tyreIntro: "正在使用小号轮胎"}
// engine: Engine {engineType: "大马力发动机", engineIntro: "正在使用大马力发动机"}
// }
主要有以下概念:
Director :指挥者,调用建造者中的不见具体实现进行部件装配,相当于整车组装厂,最终返回装配完毕的产品
Builder: 建造者含有不同部件的生产方式给构建者调用,是部件真正的生产者,但没有部件的装配流程;
product :产品 药房给访问者的复杂对象