-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObserver-pattern.php
More file actions
106 lines (91 loc) · 2.21 KB
/
Observer-pattern.php
File metadata and controls
106 lines (91 loc) · 2.21 KB
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
<?php
/**
* 观察者要实现的接口
*
* 在php SPL中已经提供SplSubject和SplOberver接口
*/
/*
* interface SplSubject {
*
* function attach(SplObserver $observer);
*
* function detach(SplObserver $observer);
*
* function notify();
* }
*
*
* interface SqlObserver {
*
* function update(SplSubject $subject);
* }
*/
/**
* 观察者模式
*
* @abstract 观察者模式定义对象的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新!
* @author xjin
* @version 201503
*/
class Subject implements SplSubject {
private $observers;
// 接收观察者对象
public function attach(SplObserver $observer)
{
if (! in_array($observer, $this->observers))
{
$this->observers[] = $observer;
}
}
// 剔除观察者对象
public function detach(SplObserver $observer)
{
if (false != ($index = array_search($observer, $this->observers)))
{
unset($this->observers[$index]);
}
}
public function post()
{
// post相关code
$this->notify();
}
// 通知被观察者
public function notify()
{
foreach ( $this->observers as $observer )
{
// 调用子类的统一方法
$observer->update($this);
}
}
// 被观察者调用的方法1
public function setCount($count)
{
echo "数据量加" . $count;
}
// 被观察者调用的方法2
public function setIntegral($integral)
{
echo "积分量加" . $integral;
}
}
// 被观察者
class Observer1 implements SplObserver {
public function update(SplSubject $SplSubject)
{
$SplSubject->setCount(1);
}
}
// 被观察者
class Observer2 implements SplObserver {
public function update(SplSubject $SplSubject)
{
$SplSubject->setIntegral(10);
}
}
// 测试内容
$subject = new Subject();
$subject->attach(new Observer1());
$subject->attach(new Observer2());
$subject->post(); // 输出:数据量加1 积分量加10