程序员

PHP SPL 观察者模式

2016-07-29  本文已影响83人  MakingChoice

PHP SPL模块中自带一个观察者模式,观察者模式是一个非常简单事件系统,包含两个或者更多交互的类,这个模式允许一个类观察另一个类的状态,当被观察的类发生变化的时候,这个模式会得到通知。<p>
在观察者模式中,被观察的叫subject,而负责观察的类叫做observe,为了表达这些内容,SPL提供了SplSubject和SplObserver接口。<p>
SplSubject接口;

interface SplSubject{
      public function attach(SplObserver $observer);
      public funtion detach(SplObserver $observer);
      public funtion notify();
}

SplObserver接口;

interface SplObserver{
      public funtion update(SplSubject $subject);
}

这个模式的概念是SplSubject类维护了一个特定状态,当这个状态发生变化时,它就会调用notify()方法。当调用notify()方法的时候,所有之前的使用的attach()方法注册的SplObserver实例的update()方法都会被调用。<p>
代码:

class demoSubject implement SplSubject{
      private $observer,$value;
      public function _construct(){
            $this->$observer=array();
      }
      public function attach(SplObserver $observer){
            $this->boserver=$observer;
      }
      public funtion detach($SplObserver $onserver){
            if($idx=array_search($observer,$this->$observer,true)){
                  unset($this->observer[$idx])
            }
      }
      public funtion notify(){
            foreach($this->$observers as $observer){
                  $observer->update($this);
             }
      }
      public funtion setValue($value){
            $this->$value=$value;
            $this->notify();
      }
      public funtion getValue(){
            return $this->$value;
      }
} 
demoObserver implements SplObserver{
    public funtion update(SplSubject $subject){
        echo 'the new value is'.$subject->getValue();
    }
}
$subject=new demoSubject();
$observer=new demoObserver();
$subject=attach($observer);
$subject->setValue();//5

观察者模式的好处是,挂接到订阅者上的观察者可多可少,并不需要提前通知 哪个类会相应subject类发出事件。

上一篇下一篇

猜你喜欢

热点阅读