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添加Xdebug扩展的方法

xdegug是一个很好的php调试扩展,安装方法也很简单,基本和其他的扩展安装方式差不多. 一、下载对应的DLL 下载地址:https://xdebug.org/download.php...

用PHP代码在网页上生成图片

用PHP代码在网页上生成图片

代码很简单,这里就不多废话了, <?php /** * Created by PhpStorm. * User: Administrator * Date: 2...

php使用COPY函数更新配置文件的方法

本文实例讲述了php使用COPY函数更新配置文件的方法。分享给大家供大家参考。具体如下: _saveconfig.php文件如下: <?php /* * File:...

[PHP]实用函数7

//打开一个到MySQL服务器的连接。成功返回连接符,失败时返回false int mysql_connect([string server[,string ...

PHP Stream_*系列函数

PHP Stream_*系列函数

下图是对这个系列函数的思维导图——我也是第一次使用思维导图这种工具。大图在这里。其中stream_socket_*系列是PHP 5新加入的处理socket连接的函数,简单方便,下一篇博客...