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通用的函数第1/2页

 但是,要成为一名PHP编程高手却并不容易。并不像很多人想象的那样,只要能够飞快地编写几条简单的代码去解决一个复杂的问题就是PHP编程高手了,真正的PHP高手还需要考虑更多的其...

由php中字符offset特征造成的绕过漏洞详解

php中的字符offset特性 php中的字符串存在一个非常有趣的特性,php中的字符串也可以像数组一样进行取值。 $test = "hello world"; echo $test...

php+ajax简单实现全选删除的方法

本文实例讲述了php+ajax简单实现全选删除的方法。分享给大家供大家参考,具体如下: <input type="checkbox" id="ckb_selectAll" on...

apache配置虚拟主机的方法详解

1.apache配置文件中打开vhost的配置LoadModule vhost_alias_module modules/mod_vhost_alias.soInclude conf/e...

采用memcache在web集群中实现session的同步会话

使用memcache来同步session是还是不错的,当然也可以通过redis来保存session,可以php开启并将Session存储到Redis缓存,下面是设置利用memcache在...