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();
  • 相关阅读:
    vuex介绍
    javascript => 方法的简写形式
    Maven学习----dependencies与dependencyManagement的区别(转)
    php加载xml编码错误,“Error: Input is not proper UTF-8, indicate encoding! ”
    SQLSERVER---- 通过位运算更改标志位
    TP框架中用tp模版迁移smarty模版的注意事项
    Maven学习----Dependency scope
    maven常见异常以及解决方法
    XAMPP部署
    自定义JS插件
  • 原文地址:https://www.cnblogs.com/phpzhou/p/4434560.html
Copyright © 2011-2022 走看看