-
Notifications
You must be signed in to change notification settings - Fork 1
/
23-工厂方法模式.php
83 lines (71 loc) · 1.35 KB
/
23-工厂方法模式.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
<?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');
/**
* 接口 - 士兵.
*/
interface IProduct
{
public function Attack(); // 攻击
}
/**
* 创建 - 步兵.
*/
class XPinfantry implements IProduct
{
public function Attack()
{
echo '步兵进攻,攻击力:10~ '.PHP_EOL;
}
}
/**
* 创建 - 骑兵.
*/
class XPcavalry implements IProduct
{
public function Attack()
{
echo '骑兵进攻,攻击力:30~ '.PHP_EOL;
}
}
/**
* 接口 - 工厂
*/
interface IServerFactory
{
public function GetInstance();
}
/**
* 创建 - 步兵工厂
*/
class ProductInfantry implements IServerFactory
{
public function GetInstance()
{
return new XPinfantry();
}
}
/**
* 创建 - 骑兵工厂
*/
class ProductCavalry implements IServerFactory
{
public function GetInstance()
{
return new XPCavalry();
}
}
$Infantry = new ProductInfantry(); // 建立步兵工厂
$Cavalry = new ProductCavalry(); // 建立骑兵工厂
$obj = [];
$obj[] = $Infantry->GetInstance(); // 生产一个步兵
$obj[] = $Cavalry->GetInstance(); // 生产一个骑兵
$obj[] = $Cavalry->GetInstance(); // 生产一个骑兵
foreach ($obj as $val) {
$val->Attack(); // 进攻
}