-
Notifications
You must be signed in to change notification settings - Fork 1
/
26-建造者模式.php
129 lines (105 loc) · 2.28 KB
/
26-建造者模式.php
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<?php
declare(strict_types=1);
/*
* This file is modified from `xiaohuangniu/26`.
*
* @see https://github.com/xiaohuangniu/26
*/
header('Content-type: text/html; charset=utf-8');
/**
* 实体 - 产品角色 - 汽车.
*/
class Car
{
public $_head; // 车头
public $_door; // 车门
public $_foot; // 车尾
public function show()
{
echo "车头的颜色:{$this->_head}".PHP_EOL;
echo "车门的颜色:{$this->_door}".PHP_EOL;
echo "车尾的颜色:{$this->_foot}".PHP_EOL;
}
}
/**
* 抽象 - 汽车的建造者.
*/
abstract class CarBuilder
{
protected $_car; // 汽车实例
public function __construct()
{
$this->_car = new Car();
}
abstract public function BuildHead(); // 改变车头颜色
abstract public function BuildDoor(); // 改变车门颜色
abstract public function BuildFoot(); // 改变车尾颜色
abstract public function GetBird(); // 返回汽车实例
}
/**
* 具体化 - 建造者 - 蓝色宝马
*/
class BlueCar extends CarBuilder
{
public function BuildHead()
{
$this->_car->_head = '蓝色';
}
public function BuildDoor()
{
$this->_car->_door = '蓝色';
}
public function BuildFoot()
{
$this->_car->_foot = '蓝色';
}
public function GetBird()
{
return $this->_car;
}
}
/**
* 具体化 - 建造者 - 红色宝马
*/
class RedCar extends CarBuilder
{
public function BuildHead()
{
$this->_car->_head = '红色';
}
public function BuildDoor()
{
$this->_car->_door = '红色';
}
public function BuildFoot()
{
$this->_car->_foot = '红色';
}
public function GetBird()
{
return $this->_car;
}
}
/**
* 实体 - 指挥者.
*/
class Director
{
// 执行改造
public function Construct($_builder)
{
$_builder->BuildHead();
$_builder->BuildDoor();
$_builder->BuildFoot();
return $_builder->GetBird();
}
}
// 测试
$director = new Director();
echo '蓝色宝马的车辆信息: '.PHP_EOL;
$blue_car = $director->Construct(new BlueCar());
$blue_car->Show();
echo PHP_EOL;
echo '红色宝马的车辆信息: '.PHP_EOL;
$red_car = $director->Construct(new RedCar());
$red_car->Show();