设计模式 建造者模式

WechatIMG26.jpeg

介绍

建造者模式是一种创建型设计模式,它允许客户端逐步构造复杂对象,而不需要知道构造过程的细节。它将对象的构造过程分离出来,使得相同的构造过程可以创建不同的表示形式。

角色

角色 说明
Builder 抽象构造者类,负责创建一个 Product 对象的各个部件指定抽象接口
ConcreteBuilder 具体构造者类,实现 Builder 的接口以构造和装配该产品的各个部件
Director 指挥者类,构造一个使用 Builder 接口的对象
Product 产品类,表示被构造的复杂对象。ConcreateBuilder 创建该产品的内部表示并定义它的装配过程

角色示例

类名 担任角色 说明
CoffeeMachine 抽象构造者 抽象咖啡机类,阐述制作一杯 Coffee 所需的配料
Nespresso 具体构造者 胶囊咖啡机类,提供 CoffeeMachine 的所需的配料并加以制作
Customer 指挥者 顾客类,使用 CoffeeMachine 来制作一杯 Coffee
Coffee 产品 咖啡类,使用 Nespresso 来制作一杯 Coffee

UML类图

建造者模式.png

代码

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php 
abstract class CoffeeMachine
{
protected $coffee;
abstract public function buildWater();
abstract public function buildCoffeeBeans();
abstract public function buildPaperCup();
abstract public function getResult();
}

class Nespresso extends CoffeeMachine
{
function __construct()
{
$this->coffee = new Coffee();
}
public function buildWater(){
$this->coffee->setWater('水');
}

public function buildCoffeeBeans(){
$this->coffee->setCoffeeBeans('咖啡豆');
}

public function buildPaperCup(){
$this->coffee->setPaperCup('纸杯');
}

public function getResult(){
return $this->coffee;
}
}

class Coffee
{
protected $water;
protected $coffeeBeans;
protected $paperCup;

public function setWater($water){
$this->water = $water;
}

public function setCoffeeBeans($coffeeBeans){
$this->coffeeBeans = $coffeeBeans;
}

public function setPaperCup($paperCup){
$this->paperCup = $paperCup;
}

public function show()
{
return "这杯咖啡由:".$this->water.'、'.$this->coffeeBeans.'和'.$this->paperCup.'组成';
}
}

class Customer
{
public $coffeeMachine;

public function startCoffeeMachine()
{
$this->coffeeMachine->buildWater();
$this->coffeeMachine->buildCoffeeBeans();
$this->coffeeMachine->buildPaperCup();
return $this->coffeeMachine->getResult();
}

public function setCoffeeMachine(CoffeeMachine $coffeeMachine)
{
$this->coffeeMachine = $coffeeMachine;
}
}

$nespresso = new Nespresso();
$customer = new Customer();
$customer->setCoffeeMachine($nespresso);
$newCoffee = $customer->startCoffeeMachine();
echo $newCoffee->show();

创建 Nespresso.php,内容如上。

执行

1
2
$ php Nespresso.php
这杯咖啡由:水、咖啡豆和纸杯组成
-------------本文结束感谢您的阅读-------------
0%