-
Notifications
You must be signed in to change notification settings - Fork 1
/
14-享元模式.php
79 lines (69 loc) · 1.54 KB
/
14-享元模式.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
<?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 AnimalInterface
{
public function getType();
}
/**
* 创建 - 鸡模型.
*/
class ChiCken implements AnimalInterface
{
public function getType()
{
echo '这是一只鸡~'.PHP_EOL;
}
}
/**
* 创建 - 猪模型.
*/
class Pig implements AnimalInterface
{
public function getType()
{
echo '这是一只猪~'.PHP_EOL;
}
}
// 农场缓存池
class Farm
{
private $_farmMap = []; // 对象缓存池
public function Produce($type)
{
// 对象缓存池判断
if (key_exists($type, $this->_farmMap)) {
echo '来自缓存池-> ';
return $this->_farmMap[$type]; // 返回缓存
}
// 建立缓存
switch ($type) {
case 'chicken':
return $this->_farmMap[$type] = new Chicken();
break;
case 'pig':
return $this->_farmMap[$type] = new Pig();
break;
}
}
}
// 初始化一个缓存池
$farm = new Farm();
// 成产一只鸡
$farm->Produce('chicken')->getType();
// 再生产一只鸡
$farm->Produce('chicken')->getType();
// 再生产一只鸡
$farm->Produce('chicken')->getType();
// 生产一只猪
$farm->Produce('pig')->getType();
// 再生产一只猪
$farm->Produce('pig')->getType();
// 再生产一只猪
$farm->Produce('pig')->getType();