-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path22-简单工厂模式.php
88 lines (76 loc) · 1.65 KB
/
22-简单工厂模式.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
<?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(); // 攻击
public function Defense(); // 防御
}
/**
* 创建 - 步兵.
*/
class XPinfantry implements IProduct
{
public function Attack()
{
echo '步兵进攻,攻击力:10~ '.PHP_EOL;
}
public function Defense()
{
echo '步兵防守,防御力:20~ '.PHP_EOL;
}
}
/**
* 创建 - 骑兵.
*/
class XPcavalry implements IProduct
{
public function Attack()
{
echo '骑兵进攻,攻击力:30~ '.PHP_EOL;
}
public function Defense()
{
echo '骑兵防守,防御力:5~ '.PHP_EOL;
}
}
/**
* 工厂角色.
*/
class ProductFactory
{
public static function GetInstance($style)
{
switch ($style) {
case 1: // 创建步兵
return new XPinfantry();
break;
case 2: // 创建骑兵
return new XPcavalry();
break;
default:
return null;
}
}
}
$obj = [];
$obj[] = ProductFactory::GetInstance(1); // 生产一个步兵
$obj[] = ProductFactory::GetInstance(2); // 生产一个骑兵
$obj[] = ProductFactory::GetInstance(3); // 生产错了
$obj[] = ProductFactory::GetInstance(2); // 生产一个骑兵
foreach ($obj as $val) {
if ($val) {
$val->Attack(); // 进攻
$val->Defense(); // 防守
} else {
echo '暂无该类兵种!'.PHP_EOL;
}
}