zoukankan      html  css  js  c++  java
  • php观察者模式

    观察者模式(有时又被称为发布/订阅模式)是软件设计模式的一种。在此种模式中,一个目标对象管理所有相依于它的观察者对象,并且在它本身的状态改变时主动发出通知。这通常透过呼叫各观察者所提供的方法来实现。此种模式通常被用来实作事件处理系统。(维基百科)

    简写一个php观察者模式的例子:

     1 <?php
     2 /**
     3  * auth phpzhou
     4  * date 2015-4-17
     5 */
     6 interface Subject{
     7     public function register(Observer $o);
     8     public function remove(Observer $o);
     9     public function notify();
    10 }
    11 
    12 interface Observer{
    13     public function update();
    14 }
    15 
    16 //具体主题
    17 class Paper implements Subject{
    18     private $_class = array();
    19     public function register(Observer $o){
    20         $this->_class[] = $o;
    21     }
    22     public function remove(Observer $o){
    23         if(!empty($this->_class)){
    24             foreach($this->_class as $key=>$observer){
    25                 if($observer == $o){
    26                     //unset($this->_class[$key]);
    27                     array_splice($this->_class,$key,1);
    28                 }
    29             }
    30             
    31         }
    32     }
    33     public function notify(){
    34         if(!empty($this->_class)){
    35             foreach($this->_class as $observer){
    36                 $observer->update();
    37             }
    38         }
    39     }
    40 }
    41 
    42 //一个观察者
    43 class CurrentObserver implements Observer{
    44     
    45     public function update(){
    46         echo "currentObserver good!",PHP_EOL;
    47     }
    48 }
    49 
    50 //一个观察者
    51 class NextObserver implements Observer{
    52     public function update(){
    53         echo "nextObserver good!",PHP_EOL;
    54     }
    55 }
    56 
    57 //测试
    58 $paper = new Paper();
    59 $paper->register(new CurrentObserver());
    60 $paper->register(new NextObserver());
    61 $paper->notify();
    62 $paper->remove(new NextObserver());
    63 echo "<br>";
    64 $paper->notify();
  • 相关阅读:
    server-conf-PPTConf
    client-autoReport-ppt
    client-autoReport-common
    浏览器书签导出
    微信公众号JSAPI支付-多公众号向同一商户号支付的问题解决
    Kettle 4.4.0 通过 Java 代码 输出日志到表
    spring tx:advice事务配置
    Spring异常捕获而且回滚事务的方法
    移动端服务器i-jetty下载编译安装及问题解决系列
    I-Jetty部署war包到安卓手机
  • 原文地址:https://www.cnblogs.com/phpzhou/p/4434560.html
Copyright © 2011-2022 走看看