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 b4351f3

Browse files
author
ZiHang Gao
committed
Added: Add factory method
1 parent 430dc84 commit b4351f3

File tree

4 files changed

+61
-4
lines changed

4 files changed

+61
-4
lines changed

‎.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Created by .ignore support plugin (hsz.mobi)
2+
.gitignore

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
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)
1010
- 建造者 [builder](https://github.com/cdoco/php-patterns/blob/master/builder.php)
11-
- 工厂方法
11+
- 工厂方法[factory_method](https://github.com/cdoco/php-patterns/blob/master/factory_method.php)
1212
- 原型
1313
- 单例
1414

‎builder.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,15 @@ function __construct() {
5858
}
5959

6060
function buildHead() {
61-
$this->person->setHead('建造头......');
61+
$this->person->setHead('建造头 ~');
6262
}
6363

6464
function buildBody() {
65-
$this->person->setBody('建造身体......');
65+
$this->person->setBody('建造身体 ~');
6666
}
6767

6868
function buildFoot() {
69-
$this->person->setFoot('建造脚......');
69+
$this->person->setFoot('建造脚 ~');
7070
}
7171

7272
function getResult() {

‎factory_method.php

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php
2+
3+
/*
4+
* 工厂方法模式
5+
*/
6+
7+
interface people {
8+
function jiehun();
9+
}
10+
11+
class man implements people {
12+
function jiehun() {
13+
echo '送玫瑰,送戒指!<br>';
14+
}
15+
}
16+
17+
class women implements people {
18+
function jiehun() {
19+
echo '穿婚纱!<br>';
20+
}
21+
}
22+
23+
// 注意了,这里是简单工厂本质区别所在,将对象的创建抽象成一个接口。
24+
interface createMan {
25+
function create();
26+
27+
}
28+
29+
class FactoryMan implements createMan {
30+
function create() {
31+
return new man;
32+
}
33+
}
34+
35+
class FactoryWomen implements createMan {
36+
function create() {
37+
return new women;
38+
}
39+
}
40+
41+
class Client {
42+
// 简单工厂里的静态方法
43+
function test() {
44+
$Factory = new FactoryMan;
45+
$man = $Factory->create();
46+
$man->jiehun();
47+
48+
$Factory = new FactoryWomen;
49+
$man = $Factory->create();
50+
$man->jiehun();
51+
}
52+
}
53+
54+
$f = new Client;
55+
$f->test();

0 commit comments

Comments
(0)

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