Home > Backend Development > PHP Tutorial > 设计模式php实例:观察者模式

设计模式php实例:观察者模式

WBOY
Release: 2016-06-20 12:30:40
Original
810 people have browsed it

当一个对象状态发生改变后,会影响到其他几个对象的改变,这时候可以用观察者模式。像wordpress这样的应用程序中,它容外部开发组开发插件,比如用户授权的博客统计插件、积分插件,这时候可以应用观察者模式,先注册这些插件,当用户发布一篇博文后,就回自动通知相应的插件更新。观察者模式符合接口隔离原则,实现了对象之间的松散耦合。观察者模式UML图:在php SPL中已经提供SplSubject和SqlOberver接口[php] view plain copyinterface SplSubject  {      function attach(SplObserver $observer);      function detach(SplObserver $observer);      function notify();  }  interface SqlObserver  {      function update(SplSubject $subject);  }  下面具体实现上面例子[php] view plain copyclass Subject implements SplSubject  {      private $observers;        public function attach(SplObserver $observer)      {          if (!in_array($observer, $this->observers)) {              $this->observers[] = $observer;          }      }          public function detach(SplObserver $observer)      {          if (false != ($index = array_search($observer, $this->observers))) {              unset($this->observers[$index]);          }      }        public function post()      {          //post相关code          $this->notify();      }        private function notify()      {          foreach ($this->observers as $observer) {              $observer->update($this);          }      }        public function setCount($count)      {          echo "数据量加" . $count;      }      public function setIntegral($integral)      {           echo "积分量加" . $integral;      }    }      class Observer1 implements SplObserver  {      public function update($subject)      {          $subject-> setCount(1);      }  }  class Observer2 implements SplObserver  {      public function update($subject)      {          $subject-> setIntegral(10);      }  }      class Client  {      public  function test()      {          $subject = new Subject();          $subject->attach(new Observer1());          $subject->attach(new Observer2());          $subject->post();//输出:数据量加1 积分量加10      }  }
Copy after login

  

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template