标签:style blog class code c http
第一次写博客,大家多多关照!欢迎拍砖哦!
我也刚学设计模式,所以记录下来。
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 |
<?php class person{ public
$name ; public
$birthday ; public
function __set( $name , $value ){ if (isset( $this -> $name )) $this -> $name = $value ; } public
function __get( $name ){ if (isset( $this -> $name )) return
$this -> $name ; } } //观察者类实现SplSubject接口,SplSubject是php内置接口 class PersonSubject implements
SplSubject{ public
$observers , $person ; public
function __construct(person $person ){ $this ->observers = new
SplObjectStorage(); $this ->person= $person ; } //增加一个观察者 public
function attach(SplObserver $observers ){ $this ->observers->attach( $observers ); } //删除一个观察者 public
function detach(SplObserver $observers ){ $this ->observers->detach( $observers ); } //达到条件时,通知观察者 public
function notify(){ foreach ( $this ->observers as
$observer ){ $observer ->update( $this ); } } //返回被观察者实例,供观察者处理 public
function getPerson(){ return
$this ->person; } } //观察者实现SplObserver接口,SplObserver是php内置接口 class fatherObserver implements
SplObserver{ //条件达到时,执行的动作 public
function update(SplSubject $splsubject ){ $person = $splsubject ->getPerson(); echo
$person ->name. ‘ 生日快乐,我是爸爸!‘ ; } } class motherObserver implements
SplObserver{ public
function update(SplSubject $splsubject ){ $person = $splsubject ->getPerson(); echo
$person ->name. ‘ 生日快乐,我是妈妈!‘ ; } } class sisterObserver implements
SplObserver{ public
function update(SplSubject $splsubject ){ $person = $splsubject ->getPerson(); echo
$person ->name. ‘ 生日快乐,我是姐姐!‘ ; } } //实例化小明 $xiaoming = new
person(); $xiaoming ->name= ‘小明‘ ; $xiaoming ->birthday= ‘0512‘ ; //绑定观察者 $subject = new
PersonSubject( $xiaoming ); $subject ->attach( new
fatherObserver); $subject ->attach( new
motherObserver); $subject ->attach( new
sisterObserver); //如果小明生日到了,通知观察者 $date = date ( ‘md‘ ,time()); if ( $xiaoming ->birthday== $date ){ $subject ->notify(); } ?> |
输出
大家自己看吧,项目中我也没用到观察者模式,郁闷!
标签:style blog class code c http
原文地址:http://www.cnblogs.com/xiaotongs/p/3724525.html