PHP实现的观察者模式实例

yipeiwu_com6年前PHP代码库

本文实例讲述了PHP实现的观察者模式。分享给大家供大家参考,具体如下:

<?php
  //定义观察者调用接口
  class transfer{
    protected $_observers = array();
    //注册对象
    public function register($sub){
      $this->_observers[] = $sub;
    }
    //外部统一调用
    public function trigger(){
      if(!empty($this->_observers)){
        foreach($this->_observers as $observer){
          $observer->update();
        }
      }
    }
  }
  //观察者接口
  interface obserable{
    public function update();
  }
  //实现观察者
  class listen implements obserable{
    public function update(){
      echo 'now first time you need to do listen<br/>';
    }
  }
  class read implements obserable{
    public function update(){
      echo 'now first time you need to read<br/>';
    }
  }
  class speak implements obserable{
    public function update(){
      echo 'now first time you need to speak<br/>';
    }
  }
  class write implements obserable{
    public function update(){
      echo 'now first time you need to write<br/>';
    }
  }
  $transfer = new transfer();
  $transfer->register(new listen());
  $transfer->register(new read());
  $transfer->register(new speak());
  $transfer->register(new write());
  $transfer->trigger();

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP基本语法入门教程》、《PHP网络编程技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

PHP易混淆函数的区别及用法汇总

本文实例分析了PHP易混淆函数的区别及用法。分享给大家供大家参考。具体分析如下: 1.echo和print的区别 PHP中echo和print的功能基本相同(输出),但是两者之间还是有细...

PHP实现将浏览历史页面网址保存到cookie的方法

本文实例讲述了PHP实现将浏览历史页面网址保存到cookie的方法。分享给大家供大家参考。具体如下: 将浏览历史页面网址保存到cookie,大致的思路如下面的代码,与实际应用有些差别。...

PHP+jQuery实现双击修改table表格功能示例

PHP+jQuery实现双击修改table表格功能示例

本文实例讲述了PHP+jQuery实现双击修改table表格功能。分享给大家供大家参考,具体如下: <!DOCTYPE html> <html lang="en"&...

PHP7.1实现的AES与RSA加密操作示例

本文实例讲述了PHP7.1实现的AES与RSA加密操作。分享给大家供大家参考,具体如下: AES: <?php header('Content-Type: text/p...

PHP实现的数组和XML文件相互转换功能示例

本文实例讲述了PHP实现的数组和XML文件相互转换功能。分享给大家供大家参考,具体如下: 最近搞微信支付,微信服务器返回的都是XML文件,所以需要转换成数组,才会便于操作,好了话不多说,...