-
Notifications
You must be signed in to change notification settings - Fork 1
/
19-代理器模式.php
73 lines (62 loc) · 1.31 KB
/
19-代理器模式.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
<?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 ShoesInterface
{
public function product();
}
/**
* 创建 - 运动鞋模型.
*/
class ShoesSport implements ShoesInterface
{
public function product()
{
echo '生产一双球鞋'.PHP_EOL;
}
}
/**
* 代理器.
*/
class Proxy
{
private $_shoes; // 鞋的模型对象
private $_shoesType; // 生产哪种鞋子
public function __construct($shoesType)
{
$this->_shoesType = $shoesType;
}
/**
* 生产.
*/
public function product()
{
switch ($this->_shoesType) {
case 'sport':
echo '我可以偷工减料';
$this->_shoes = new ShoesSport();
break;
default:
throw new Exception('类型不正确', 404);
break;
}
$this->_shoes->product();
}
}
echo '未加代理之前:'.PHP_EOL;
// 生产运动鞋
$shoesSport = new ShoesSport();
$shoesSport->product();
echo '加代理:'.PHP_EOL;
// 把运动鞋产品线外包给代工厂
$proxy = new Proxy('sport');
// 代工厂生产运动鞋
$proxy->product();