0%

建造者模式

建造者模式

也称为生成器模式,将一个复杂对象的构建与它的表示分离,使用同样的构建过程可以创建不同的表示

核心概念

  • Builder 建造者接口,定义创建一个Product对象所需要的各个部件的操作
  • ConcreteBuilder 具体的构造者实现,实现各个部件的创建,并负责组装Product对象的各个部件,同时还提供一个让用户获取组装完成后的产品对象的方法
  • Director 指导者,用来使用Builder接口,以一个统一的过程来构建所需的Product对象
  • Product 产品,表示被建造者构建的复杂对象
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
public class Struct1{...}
public class Struct2{...}

public class Product{
Struct1 struct1;
Struct2 struct2;
}

public interface IBuild{
public void createStruct1();
public void createStruct2();
public Product composite();
public Product create();
}
public class BuildProduct implements IBuild{
Product p = new Product();
public void createStruct1(){
//p.struct1 = ...
//p.struct2 = ...
}
public Product create(){
return composite();
}

}


public class Director{
private IBuild build;
public Director(IBuild build){
this.build = buid;
}
public Product build(){
build.create();
}
public static void main(){
IBuild build = new BuildProduct();
Director direcotr = new Director(build);
Prodcut p = director.build();
}
}

优缺点

优点

  • 封装性,客户端不必知道产品内部组成的细节
  • 具体的建造者之间是相互独立的,有利于扩展,可以将过程逐步细化,而不会对其他模块产生影响
  • 更好的复用性

缺点

  • 使用场景

  • 多个部件都可以装配到一个对象中,结构比较复杂

  • 需要生成的产品对象的属性相互依赖

  • 同一个构建过程有着不同的表示

欢迎关注我的其它发布渠道