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

    观察者模式有时也被称作发布/订阅模式,该模式用于为对象实现发布/订阅功能:一旦主体对象状态发生改变,与之关联的观察者对象会收到通知,并进行相应操作。

     1 <?php
     2 
     3 /**
     4  * 观察者接口
     5  */
     6 interface ObserverInterface
     7 {
     8     public function update($params);
     9 }
    10 
    11 /**
    12  * 被观察者接口
    13  */
    14 interface BeenObservedInterface
    15 {
    16     public function attach(ObserverInterface $observer);
    17     public function detach(ObserverInterface $observer);
    18     public function notify();
    19 }
    20 
    21 
    22 
    23 class Observer implements ObserverInterface
    24 {
    25     public function update($params)
    26     {
    27         $reflection = new ReflectionClass($params);
    28         echo "<br/>The Button(BeenObserved) ".$reflection->getName()." has been clicked!";
    29     }
    30 }
    31 
    32 
    33 class BeenObserved implements BeenObservedInterface
    34 {
    35     private $_observers;
    36 
    37     public function attach(ObserverInterface $observer)
    38     {
    39         $this->_observers[spl_object_hash($observer)] = $observer;
    40     }
    41 
    42     public function detach(ObserverInterface $observer)
    43     {
    44         unset($this->_observers[spl_object_hash($observer)]);
    45     }
    46 
    47     public function notify()
    48     {
    49         foreach ($this->_observers as $observer) {
    50             $observer->update($observer);
    51         }
    52     }
    53 
    54     public function test()
    55     {
    56         $this->notify();
    57     }
    58 }
    59 
    60 
    61 
    62 $observer = new Observer();
    63 $observer2 = new Observer();
    64 $beenObserved = new BeenObserved();
    65 
    66 $beenObserved->attach($observer);
    67 $beenObserved->attach($observer2);
    68 
    69 $beenObserved->test();
    View Code
  • 相关阅读:
    Ecshop去掉模版中随机出现Ecshop版权的方法
    ecshop邮件订阅按“订阅”没反应
    ecshop开发帮助
    ecshop循环计数
    ECSHOP购物车页面显示商品简单描述
    ecshop 函数列表大全
    ecshop 商品分类页 取得当前分类下的子分类方法
    ecshop调用指定分类和个数的文章列表
    thymeleaf中的th:assert用法
    thymeleaf中的模板布局
  • 原文地址:https://www.cnblogs.com/hangtt/p/6262586.html
Copyright © 2011-2022 走看看