2010-06-23 38 views

回答

0

Ummmm ....单

2

单身但我总是在使用前总是三思而后行。

3

你真的需要考虑你的具体情况。在决定您需要哪些功能时,请注意以下几种模式。通常,Singleton可以与服务定位器或工厂一起使用。

Singleton

Service Locator

Factories

1

下面是PHP的Singleton模式的例子。从技术上讲,它最多允许创建两个实例,但嘎嘎叫着在构造函数时的实例已经存在:

<?php 

class Singleton { 

static protected $_singleton = null; 

function __construct() { 
    if (!is_null(self::$_singleton)) 
    throw new Exception("Singleton can be instantiated only once!"); 
    self::$_singleton= $this; 
} 

static public function get() { 
    if (is_null(self::$_singleton)) 
    new Singleton(); 
    return self::$_singleton; 
} 

} 

$s = new Singleton(); 
var_dump($s); 
$s2 = Singleton::get(); 
var_dump($s2); // $s and $s2 are the same instance. 
$s3 = new Singleton(); // exception thrown 
var_dump($s3); 

你也想看看__clone取决于你需要如何严格地控制实例调用。

+1

为什么不使构造函数为私有? – mmattax 2010-06-23 20:02:04

+0

私人构造函数?不知道PHP支持他们。 NICE – leepowers 2010-06-23 21:04:29

1

您正在寻找Singleton模式。

 

class Foo { 

    private static $instance = null; 

    private function __construct() { } 

    public static function instance() { 

     if(is_null(self::$instance)) 
      self::$instance = new Foo; 

     return self::$instance; 
    } 

    public function bar() { 
     ... 
    } 
} 

$foo = Foo::instance(); 
$foo->bar();