-
Notifications
You must be signed in to change notification settings - Fork 1
/
07-访问者模式.php
165 lines (141 loc) · 2.97 KB
/
07-访问者模式.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
<?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');
/**
* 抽象出 实体类.
*/
abstract class Entity
{
public $people_name; // 人的名称
/**
* 触发行为
* $Visitor 对应行为的实例.
* @param mixed $Visitor
*/
abstract public function Accept($Visitor);
}
/**
* 创建一个 男性.
*/
class VMan extends Entity
{
public function __construct()
{
$this->people_name = '男人';
}
public function Accept($Visitor)
{
$Visitor->VManRelease($this);
}
}
/**
* 创建一个 女性.
*/
class VWoman extends Entity
{
public function __construct()
{
$this->people_name = '女人';
}
public function Accept($Visitor)
{
$Visitor->VWomanRelease($this);
}
}
/**
* 抽象出 行为类.
*/
abstract class Behavior
{
protected $bh_name;
/**
* 行为逻辑 - 男性
* $ResNew 对应实体的实例.
* @param mixed $ResNew
*/
abstract public function VManRelease($ResNew);
/**
* 行为逻辑 - 女性
* $ResNew 对应实体的实例.
* @param mixed $ResNew
*/
abstract public function VWomanRelease($ResNew);
}
/**
* 创建一个 吃东西行为.
*/
class Eat extends Behavior
{
public function __construct()
{
$this->bh_name = '吃东西';
}
public function VManRelease($VMan)
{
echo "{$VMan->people_name} : {$this->bh_name}时,都很粗鲁。".PHP_EOL;
}
public function VWomanRelease($VMan)
{
echo "{$VMan->people_name} : {$this->bh_name}时,都很斯文。".PHP_EOL;
}
}
/**
* 创建一个 运动行为.
*/
class Motion extends Behavior
{
public function __construct()
{
$this->bh_name = '运动';
}
public function VManRelease($VMan)
{
echo "{$VMan->people_name} : {$this->bh_name}时,大汗淋漓。".PHP_EOL;
}
public function VWomanRelease($VMan)
{
echo "{$VMan->people_name} : {$this->bh_name}时,休闲漫步。".PHP_EOL;
}
}
/**
* 设计一个 结构对象类,用于聚合实体信息.
*/
class Object
{
private $entity = []; // 存储实体对象
// 新增实体
public function Add($entity)
{
array_push($this->entity, $entity);
}
// 移除实体
public function Remove($entity)
{
foreach ($this->entity as $k => $v) {
if ($v == $entity) {
unset($this->entity[$k]);
break;
}
}
}
// 查看对应行为描述
public function Display($Visitor)
{
foreach ($this->entity as $v) {
$v->Accept($Visitor);
}
}
}
// 先聚合实体
$os = new Object();
$os->Add(new VMan());
$os->Add(new VWoman());
// 查看吃东西的行为
$os->Display(new Eat());
// 查看运动的行为
$os->Display(new Motion());