白筱汐

想都是问题,做都是答案

0%

JavaScript设计模式——建造者模式

介绍

建造者模式又称生成器模式,分步构建一个复杂对象,并允许按步骤构造。同样的构建过程可以采用不同的表示,将一个复杂对象的构建层与其表示层分离。

js代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 建造者,部件生产
class ProductBuilder {
constructor(param) {
this.param = param
}

/* 生产部件,part1 */
buildPart1() {
// ... Part1 生产过程
this.part1 = 'part1'

}

/* 生产部件,part2 */
buildPart2() {
// ... Part2 生产过程
this.part2 = 'part2'
}
}

/* 指挥者,负责最终产品的装配 */
class Director {
constructor(param) {
const _product = new ProductBuilder(param)
_product.buildPart1()
_product.buildPart2()
return _product
}
}

// 获得产品实例
const product = new Director('param')

console.log(product);