观察者模式

1 <?php
 2     //定义观察者调用接口
 3     class transfer{
 4         protected $_observers = array();
 5         
 6         //注册对象
 7         public function register($sub){
 8             $this->_observers[] = $sub;    
 9         }
10         
11         //外部统一调用
12         public function trigger(){
13             if(!empty($this->_observers)){
14                 foreach($this->_observers as $observer){
15                     $observer->update();
16                 }    
17             }
18         }
19     }
20     
21     //观察者接口
22     interface obserable{
23         public function update();
24     }
25     
26     //实现观察者
27     class listen implements obserable{
28         public function update(){
29             echo 'now first time you need to do listen<br/>';
30         }
31     }
32     
33     class read implements obserable{
34         public function update(){
35             echo 'now first time you need to read<br/>';
36         }
37     }
38     
39     class speak implements obserable{
40         public function update(){
41             echo 'now first time you need to speak<br/>';
42         }
43     }
44     
45     class write implements obserable{
46         public function update(){
47             echo 'now first time you need to write<br/>';
48         }
49     }
50     
51     $transfer = new transfer();
52     $transfer->register(new listen());
53     $transfer->register(new read());
54     $transfer->register(new speak());
55     $transfer->register(new write());
56     $transfer->trigger();
posted @ 2017-04-29 19:55  余磊  阅读(118)  评论(0编辑  收藏  举报
友情链接:回力旗舰店 | 中老年女装 | 新航道 | 托福培训 | 雅思报名费用