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
|
<?php
/**
*
* 被观察者
*
*/
class
Subject
implements
SplSubject {
protected
$_value
;
protected
$_observers
;
/**
* 构造函数
*
* @return void
*/
public
function
__construct() {
$this
->_observers =
new
SplObjectStorage();
}
/**
* 追加观察者
* @see SplSubject::attach()
*/
public
function
attach(SplObserver
$observer
) {
$this
->_observers->attach(
$observer
);
}
/**
* 抛弃观察者
* @see SplSubject::detach()
*/
public
function
detach(SplObserver
$observer
) {
$this
->_observers->detach(
$observer
);
}
/**
* 通知观察者
* @see SplSubject::notify()
*/
public
function
notify() {
foreach
(
$this
->_observers
as
$observer
) {
$observer
->update(
$this
);
}
}
/**
* 设置最新值
*
* @param mixed $value
* @return
*/
public
function
setValue(
$value
) {
$this
->_value =
$value
;
$this
->notify();
}
/**
* 获取最后更新的值
*
* @return mixed
*/
public
function
getValue() {
return
$this
->_value;
}
}
/**
* 观察者
*
*/
class
Observer
implements
SplObserver {
/\**
* @see SplObserver::update()
*/
public
function
update(SplSubject
$subject
) {
echo
'i know you '
.
$subject
->getValue();
}
}
header(
'Content-type:text/html;charset=utf-8'
);
date_default_timezone_set(
'Asia/Shanghai'
);
error_reporting
(E_ALL);
$subject
=
new
Subject();
$observer
=
new
Observer();
$subject
->attach(
$observer
);
$subject
->setValue(
'updated'
);
|
本文转自shayang8851CTO博客,原文链接:http://blog.51cto.com/janephp/1286698,如需转载请自行联系原作者