Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 430dc84

Browse files
cdocoZiHang Gao
authored and
ZiHang Gao
committed
Added: 添加建造者模式
1 parent 7b17f7b commit 430dc84

File tree

2 files changed

+94
-1
lines changed

2 files changed

+94
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
- 简单工厂 [simple_factory](https://github.com/cdoco/php-patterns/blob/master/simple_factory.php)
99
- 抽象工厂 [abstract_factory](https://github.com/cdoco/php-patterns/blob/master/abstract_factory.php)
10-
- 建造者
10+
- 建造者[builder](https://github.com/cdoco/php-patterns/blob/master/builder.php)
1111
- 工厂方法
1212
- 原型
1313
- 单例

‎builder.php

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
<?php
2+
3+
/**
4+
* 建造者模式
5+
*/
6+
class Person {
7+
private $head;
8+
private $body;
9+
private $foot;
10+
11+
//头
12+
public function getHead() {
13+
return $this->head;
14+
}
15+
16+
public function setHead($head) {
17+
$this->head = $head;
18+
}
19+
20+
//体
21+
public function getBody() {
22+
return $this->body;
23+
}
24+
25+
public function setBody($body) {
26+
$this->body = $body;
27+
}
28+
29+
//脚
30+
public function getFoot() {
31+
return $this->foot;
32+
}
33+
34+
public function setFoot($foot) {
35+
$this->foot = $foot;
36+
}
37+
}
38+
39+
//创建一个product对象的各个部件指定抽象接口
40+
interface PersonBuilder {
41+
42+
public function buildHead();
43+
44+
public function buildBody();
45+
46+
public function buildFoot();
47+
48+
//产品返还方法
49+
public function getResult();
50+
}
51+
52+
//实现接口
53+
class ConcreteBuilder implements PersonBuilder {
54+
private $person;
55+
56+
function __construct() {
57+
$this->person = new Person();
58+
}
59+
60+
function buildHead() {
61+
$this->person->setHead('建造头......');
62+
}
63+
64+
function buildBody() {
65+
$this->person->setBody('建造身体......');
66+
}
67+
68+
function buildFoot() {
69+
$this->person->setFoot('建造脚......');
70+
}
71+
72+
function getResult() {
73+
return $this->person;
74+
}
75+
}
76+
77+
//指导者
78+
class Director {
79+
80+
public function __construct(ConcreteBuilder $builder) {
81+
$builder->buildHead();
82+
$builder->buildBody();
83+
$builder->buildFoot();
84+
}
85+
}
86+
87+
//Test
88+
$builder = new ConcreteBuilder();
89+
$director = new Director($builder);
90+
$person = $builder->getResult();
91+
echo $person->getHead();
92+
echo $person->getBody();
93+
echo $person->getFoot();

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /