想分享的几种设计模式
目前模式:工厂模式,单例模式,适配器模式,装饰者模式,建造者模式
建造者模式
简介:建造者模式(builder pattern)比较简单,它属于创建型模式的一种。
白话:4个部分:有个产品,有个工厂可以造产品,有个设计师指挥造多少,有个人想买产品。
买产品的用户不介意产品制造流程,只需要产品!
function Cola() {
this.sugar = '50g',
this.water = '100g'
}
function Packing() {
// 第一种打包方式
this.createPkg = function(){
console.log('创建可乐外皮')
}
this.pushCola = function() {
console.log('可乐倒进瓶子')
}
this.complete = function() {
var cola = new Cola()
cola.complete = true
return cola
}
this.init = function() {
this.createPkg() // 创建外皮
this.pushCola() // 倒进瓶子
//还可以增加其他步骤
return this.complete() // 制作完成
}
}
function greenPacking() {
//绿皮可乐打包方式
this.createPkg = function(){
console.log('创建green可乐外皮')
}
this.pushCola = function() {
console.log('可乐倒进green瓶子')
}
this.complete = function() {
var cola = new Cola()
cola.complete = true
return cola
}
this.init = function() {
this.createPkg() // 创建外皮
this.pushCola() // 倒进瓶子
//还可以增加其他步骤
return this.complete() // 制作完成
}
}
function Boss() {
this.createCola = function(packType) {
const pack = new window[packType]
this.product = pack.init() //完整产品产出
}
this.getCola = function(packType) {
this.createCola(packType);
return this.product
}
}
const boss = new Boss()
var UserCola = boss.getCola('greenPacking') // UserCola.complete === true
其他东西都不要,只要最后生产好的Cola,有sugar,有water。
关键在于Boss 函数中,担任一个整合的职责
同样的Boss函数,我可以通过更换Packing函数,打包方式,获得不同样式的Cola。
通过给getCola函数传入不同想要的参数,获得不同的最终产品。实现了可插拔的函数结构。