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

PHP
在PHP中以root身份运行外部命令
PHP编程常用技巧四则
实例学习PHP之投票程序篇
PHP中的加密功能
PHP VS ASP
PHP生成动态WAP页面
PHP中for循环语句的几种变型
PHP5.0对象模型探索之对象串行化
PHP5.0对象模型探索之重载
浅议PHP程序开发中的模板选择
用PHP写的身份证验证程序
PHP.MVC的模板标签系统之初识PHP.MVC
PHP程序加速探索之代码优化
PHP程序加速探索之压缩输出gzip
用PHP文件上传的具体思路及实现
使用PHP编写基于Web的文件管理系统
理解PHP中的MVC编程之控制器
PHP程序加速探索之缓存输出
让你的PHP引擎全速运转的三个绝招
PHP程序加速探索之加速工具软件

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 170 ::
收藏到网摘: 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();  
}