-
Notifications
You must be signed in to change notification settings - Fork 0
/
observe.php
58 lines (57 loc) · 1.15 KB
/
observe.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
<?php
/**
* 观察者模式
* User: zhuxinlei
* Date: 2018/6/4
* Time: 下午11:55
*/
//被观察者接口
interface Observable{
function add(observe $observe);
function del(observe $observe);
function notify();
}
//订单被观察者
class order implements Observable{
private $instance=array();
function add(observe $observe)
{
$key = array_search($observe,$this->instance);
if($key === false){
$this->instance[] = $observe;
}
}
function del(observe $observe)
{
$key = array_search($observe,$this->instance);
if($key !== false){
unset($this->instance[$key]);
}
}
function notify()
{
foreach($this->instance as $key=>$val){
$val->update();
}
}
}
interface observe{
function update();
}
class Email implements observe{
function update(){
echo '发送邮件';
}
}
class Message implements observe{
function update(){
echo '发送短信';
}
}
//客户端调用
$order = new order();
$order->add(new Email());
$order->add(new Message());
$order->del(new Email());
$order->notify();
?>