php中的观察者模式简单实例

  观察者模式是设计模式中比较常见的一个模式,包含两个或者更多的互相交互的类。这一模式允许某个类观察另外一个类的状态,当被观察类的状态发生变化时候,观察者会进行得到通知进而更新相应状态。

  php的SPL标准类库提供了SplSubject和SplObserver接口来实现,被观察的类叫subject,负责观察的类叫observer。这一模式是SplSubject类维护了一个特定状态,

  当这个状态发生变化时候,它就会调用notify方法。调用notify方法时,所有之前使用attach方法注册的SplObserver实例的update方法都会调用,Demo如下:

  

复制代码 代码如下:

  class DemoSubject implements SplSubject{

  private $observers, $value;

  public function __construct(){

  $this->observers = array();

  }

  public function attach(SplObserver $observer){

  $this->observers[] = $observer;

  }

  public function detach(SplObserver $observer){

  if($idx = array_search($observer, $this->observers, true)){

  unset($this->observers[$idx]);

  }

  }

  public function notify(){

  foreach($this->observers as $observer){

  $observer->update($this);

  }

  }

  public function setValue($value){

  $this->value = $value;

  $this->notify();

  }

  public function getValue(){

  return $this->value;

  }

  }

  class DemoObserver implements SplObserver{

  public function update(SplSubject $subject){

  echo 'The new value is '. $subject->getValue();

  }

  }

  $subject = new DemoSubject();

  $observer = new DemoObserver();

  $subject->attach($observer);

  $subject->setValue(5);