zoukankan      html  css  js  c++  java
  • 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');
    
      
    
  • 相关阅读:
    面试范围
    Spark集群基础概念 与 spark架构原理
    RDD 算子补充
    常用Actoin算子 与 内存管理 、共享变量、内存机制
    常用Transformation算子
    spark core (二)
    Spark 介绍
    JSON对象和string的相互转换
    javascript中substring和substr方法
    mongodb学习相关网址
  • 原文地址:https://www.cnblogs.com/happy-dream/p/6565206.html
Copyright © 2011-2022 走看看