当前位置: 首页 > 图文教程 > 网络编程 > PHP > php4和php5单态模式(Singleton Pattern)写法

PHP
在PHP的图形函数中显示汉字
PHP中显示格式化的用户输入
php做饼图的函数
用PHP实现登陆验证码(类似条行码状)
PHP安全配置(1)
PHP安全配置(2)
PHP安全配置(3)
PHP安全配置(4)
水火也相容!巧妙在IIS中配置PHP调试环境
建立PHP的本地调试环境
php通用检测函数集(1)
php通用检测函数集(2)判断是否为有效网址
php通用检测函数集(3)
代码实例之php通用检测函数集(4)
php通用检测函数集(5)
使用php通过smtp发送邮件新手指南
使用PHP维护文件系统
PHP文件上传的具体思路及实现
回帖脱衣服的图片实现
用php实现qq挂机

PHP 中的 php4和php5单态模式(Singleton Pattern)写法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 166 ::
收藏到网摘: n/a

单态模式(Singleton Pattern) 就是一个类Class只有一个实例存在。(Ensure a class only has one instance, and provide a global point of access to it.)
这个是php5的写法。

以下为引用的内容:
<?php
class SingletonPhp5{
 static private $_instance=null;

 function getInstance(){
  if(! self::$_instance){
   self::$_instance=new self;
  }
  return self::$_instance;
 }

 function __construct(){

 }

 function Show(){
  echo 'Singleton on Php5';
 }
}

{
 $Singleton=SingletonPhp5::getInstance()->Show();
}

这个是php4的写法,当然此方法在php5下也可以正常运行。

以下为引用的内容:

class SingletonPhp4{      
   function &getInstance(){          
     static $_instance=array();          
     if(empty($_instance)){              
         $_instance[]= & new SingletonPhp4();  
        
}          
  return $_instance[0];      

  }
        
function SingletonPhp4(){        

}        

function Show(){          
   echo 'Singleton on Php4';      
   }  
}    

{      
   $Singleton=SingletonPhp4::getInstance();      
   $Singleton->Show();  
}