说明
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。首先看下关系图:
示例
下面讲解下设计模式的代码实现
- 创建产品类
1
2
3
4
5
6
7
8
9class Product{
private $parts = [];
public function add(string $part): void{
$this->parts[] = $part;
}
public function show():void{
print_r($this->parts);
}
} - 创建建造者接口
1
2
3
4
5interface Builder{
public function buildPartA(): void;
public function buildPartB(): void;
public function getResult(): 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
33class ConcreteBuilder1 implements Builder{
private $product;
public function __construct(){
$this->product = new Product();
}
public function buildPartA(): void{
$this->product->add('部件A');
}
public function buildPartB(): void{
$this->product->add('部件B');
}
public function getResult(): Product{
return $this->product;
}
}
class ConcreteBuilder2 implements Builder{
private $product;
public function __construct(){
$this->product = new Product();
}
public function buildPartA(): void{
$this->product->add('部件X');
}
public function buildPartB(): void{
$this->product->add('部件Y');
}
public function getResult(): Product{
return $this->product;
}
}创建构造器
1
2
3
4
5
6class Director{
public function construct(Builder $builder){
$builder->buildPartA();
$builder->buildPartB();
}
}
我们来测试下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15class FactoryTest{
public static function index(){
$director = new Director();
$builder1 = new ConcreteBuilder1();
$builder2 = new ConcreteBuilder2();
$director->construct($builder1);
$product1 = $builder1->getResult();
$product1->show();
$director->construct($builder2);
$product2 = $builder2->getResult();
$product2->show();
}
}输出结果为:
1
2Array ( [0] => 部件A [1] => 部件B )
Array ( [0] => 部件X [1] => 部件Y )
总结
它与工厂模式的区别就是:工厂模式关注的是创建单个产品,而建造者模式则关注创建复合对象,多个部分。