首页 > 代码库 > 观察者模式
观察者模式
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();
观察者模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。