码迷,mamicode.com
首页 > Web开发 > 详细

PHP设计模式-观察者

时间:2016-07-13 12:03:19      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:观察者

PHP设计模式-观察者

   一个对象状态发生改变后,会影响到其他几个对象的改变,这时候可以用观察者模式。一个对象通过添加一个attach方法允许观察者注册自己,使本身变得可观察。当被观察的对象更改时,它会将消息发送到已注册的观察者。观察者使用该信息执行的操作与被观察的对象无关。观察者模式是一种事件系统,意味着这一模式允许某些类通过观察被观察类的状态变化,做出相应的动作。

   观察者模式UML图

技术分享

  php5中提供了观察者observer与被观察者subject接口

   interface SplSubject  

    {  

    function attach(SplObserver $observer);  

    function detach(SplObserver $observer);  

    function notify();  

    }  

   interface SqlObserver  

    {  

    function update(SplSubject $subject);  

    }

  例子如下

<?php
  class user implements SplSubject{
  public     $lognum;
  public     $hobby;
  protected  $observers;
  
  public function __construct($hobby){
      $this->lognum= rand(1,10);
      $this->hobby= $hobby;
      $this->observers=new SplObjectStorage();
  }
  public function login(){
    $this->notify();
  }
  
  public function attach(SPLObserver $observer){
    $this->observers->attach($observer);
  }
  
  public function detach(SPLObserver $observer){
      $this->observers->detach($observer);
  }
  
  public function notify(){
      $this->observers->rewind();
      while($this->observers->valid){
         $observer= $this->observers->current();
         $observer->update($this);
         $this->observers->next();
      }      
  }    
  }
   
  class secrity implements SPLObserver{
      
      public function update(SplSubject $subject){
          if($subject->lognum>=3){
              
          }else{
              
          }          
      }
  }
    
  class ad implements SPLObserver{
  
      public function update(SplSubject $subject){
          if($subject->hobby=="sports"){
  
          }else{
  
          }  
      }
  }
  
  //实施观察
  $user= new user("sports");
  $user->attach(new secrity());
  $user->attach(new ad());
  $user->login();
  
  ?>


本文出自 “残梦” 博客,谢绝转载!

PHP设计模式-观察者

标签:观察者

原文地址:http://2964813.blog.51cto.com/2954813/1825993

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!