建造者模式
Max Zhang Lv4

建造者模式

建造者模式是一种创建型设计模式,它可以将一个复杂对象的构建过程与其表示分离,使得同样的构建过程可以创建不同的表示。核心思想是将构建过程封装在一个独立的类中,使得构建过程可以灵活地组合。

优点

  • 将构建过程与表示分离,使得同样的构建过程可以创建不同的表示。
  • 可以灵活地组合构建过程,构建不同的表示。
  • 可以控制构建过程的细节,使得构建过程更加清晰。

缺点

  • 增加了系统的复杂度,需要引入新的类。
  • 增加了系统的开销,需要额外的开销来维护构建过程。

适用场景

  • 需要创建一个复杂对象,且构建过程比较复杂。
  • 需要创建一个对象的表示与构建过程分离。
  • 需要灵活地组合构建过程,构建不同的表示。

示例

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Product {
private parts: string[] = [];

addPart(part: string) {
this.parts.push(part);
}

show() {
console.log(this.parts.join(", "));
}
}

interface Builder {
buildPartA(): void;
buildPartB(): void;
buildPartC(): void;
getResult(): Product;
}

class ConcreteBuilder implements Builder {
private product: Product = new Product();

buildPartA() {
this.product.addPart("Part A");
}

buildPartB() {
this.product.addPart("Part B");
}

buildPartC() {
this.product.addPart("Part C");
}

getResult() {
return this.product;
}
}

class Director {
private builder: Builder;

constructor(builder: Builder) {
this.builder = builder;
}

construct() {
this.builder.buildPartA();
this.builder.buildPartB();
this.builder.buildPartC();
}
}

const builder = new ConcreteBuilder();
const director = new Director(builder);

director.construct();

const product = builder.getResult();
product.show();

建造者模式是将复杂对象的构建过程与表示分离,使得同样的构建过程可以创建不同的表示。但如果对象的构建是一个接一个的,并且每一个对象的创建都要依赖上一个对象的创建,那么建造者模式就不适用了。

 评论
评论插件加载失败
正在加载评论插件