Home  >  Article  >  php教程  >  php设计模式之单例、多例设计模式的应用分析

php设计模式之单例、多例设计模式的应用分析

WBOY
WBOYOriginal
2016-06-13 11:43:40848browse

单例(Singleton)模式和不常见的多例(Multiton)模式控制着应用程序中类的数量。如模式名称,单例只能实例化一次,只有一个对象,多例模式可以多次实例化。

基于Singleton的特性,我们经常用Singleton配置应用程序并定义应用程序中可能随时访问的变量。但有时并不推荐使用Singleton,因为它生成了一个全局状态且

该单一根对象没有封装任何系统功能。多数情况下,会使单元测试和调试变得困难。读者根据情况自行决定。
代码示例:

复制代码 代码如下:


class SingletonExample{
    private function __construct(){}//防止直接实例化
  public static function getInstance(){ //不与任何对象有关联
 static $instance=null;    //调用此函数的所有代码共享该变量,不必要让其是类的静态变量
 if($instance==null){
   $instance=new SingletonExample();
     }
   return $instance;
  }
}
$obj1=SingletonExample::getInstance();
$obj2=SingletonExample::getInstance();
var_dump($obj1===$obj2);// true   是同一个实例
?>


Multiton与singleton相似,不同的是后者需要getInstance()函数传递关键值。
对于给定的关键值只会存在唯一的对象实例,如果有多个节点,每个节点拥有唯一的表识符,且各个节点在某单次执行(如cms里的节点)可能出现多次,那么就可以用Multiton模式实现这些节点啊,Multiton节省内存,并确保同一个对象的多个实例不发生冲突.
示例:

复制代码 代码如下:


  class MultitonExample{
 private function __construct(){}//防止直接实例化

   public static function getInstance($key){
  static $instance=array();   
  if(!array_key_exists($key,$instance)){
    $instance[$key]=new SingletonExample();
      }
    return $instance($key);
   }
 };
 ?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn