PHP实现的观察者模式实例

yipeiwu_com5年前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中的Cannot modify header information 问题

完美解决PHP中的Cannot modify header information 问题

我就遇到这种问题,网上找到这个解决的方案,就收藏下写PHP的朋友们肯定遇到过这样一个问题:通过header函数改变http协议头的时候,会出现一个类似下面格式的warning:复制代码...

关于php开启错误提示的总结

第一种方法:在php.ini文件里改变display_errors和error_reporting的值,没有的直接加上 ; 第一处修改 ; display_errors = Off...

php自定义函数br2nl实现将html中br换行符转换为文本输入中换行符的方法【与函数nl2br功能相反】

本文实例讲述了php自定义函数br2nl实现将html中br换行符转换为文本输入中换行符的方法。分享给大家供大家参考,具体如下: 下面这几个方法将能够帮你解决这个问题。 PHP版将htm...

php discuz 主题表和回帖表的设计

php discuz 主题表和回帖表的设计

以下内容仅摘录部分:如果由我们来设计主题表和回帖表,通常的做法是如下。        这样在获取主题列表时,直接使用...

php flush类输出缓冲剖析

<?php for ($i=10; $i>0; $i--) { echo $i; flush(); sleep(1); } ?> 按照php手册里的说法 该函数将当前为...