php 观察者模式

观察者模式

在面向对象中,主题就是提供注册和通知的接口,观察者提供操作的接口;观察者利用主题的接口香猪蹄注册,主题利用观察者的接口通知观察者,这样程序代码的耦合度就低;

在面向对象中,复用类的方法有很多,尽量多用组合实现,这样代码的耦合度就比较低,容易后续扩展;

代码示例

<?php  
   abstract class subject
   {
	   protected $observers;
	   public function addobserver($key,Equipment $observer)
	   {
		   $this->observers[$key] = $observer;
	   }
   }

   abstract class Equipment
   {
       abstract function update($temp);
       abstract function display();
   }

   class weather extends subject
   {
       private $_temp;
       public function notify()
       {
           foreach($this->observers as $observe)
           {
                $observe->update($this->_temp);
           }
       }
       public function datachange($temp)
       {
           $this->_temp = $temp;

           $this->notify();
       }
   }
   class ipad extends Equipment
   {
       private $_temp;
       public function update($temp)
       {
           $this->_temp = $temp;
           $this->display();
       }
       public function display()
       {
           echo $this->_temp;
       }
   }

   $observe_ipad = new ipad();

   $weather = new weather();

   $weather->addobserver('ipad',$observe_ipad);

   $weather->datachange('38');

  
原文地址:https://www.cnblogs.com/happy-dream/p/6565206.html