-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChainOfResponsibilities.php
73 lines (63 loc) · 1.38 KB
/
ChainOfResponsibilities.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
/**
* 责任链模式
*
* 按责任链顺序调用,当一个处理器无法处理的时候就调用下一个处理器处理
*/
abstract class Handler
{
/**
* @var Handler
*/
protected $next;
public function __construct(Handler $handler = null)
{
$this->next = $handler;
}
public final function handle($data)
{
$result = $this->process($data);
if ($result === null && $this->next !== null) {
$result = $this->next->handle($data);
}
return $result;
}
abstract public function process($data);
}
class CpuCache extends Handler
{
public function process($data)
{
if ($data === 'cpu') {
return "来自处理器缓存\n";
}
return null;
}
}
class MemoryCache extends Handler
{
public function process($data)
{
if ($data === 'memory') {
return "来自内存缓存\n";
}
return null;
}
}
class DiskCache extends Handler
{
public function process($data)
{
if ($data === 'disk') {
return "来自磁盘缓存\n";
}
return null;
}
}
$handler = (new CpuCache(new MemoryCache(new DiskCache())));
echo $handler->handle('cpu');
echo $handler->handle('memory');
echo $handler->handle('disk');
// 来自处理器缓存
// 来自内存缓存
// 来自磁盘缓存