PHP實現單例模式最安全的做法_php執行個體

來源:互聯網
上載者:User

作為一種常用的設計模式,單例模式被廣泛的使用。那麼如何設計一個單例才是最好的呢?

通常我們會這麼寫,網上能搜到的例子也大部分是這樣:

複製代碼 代碼如下:

class A
{
    protected static $_instance = null;
    protected function __construct()
    {
        //disallow new instance
    }
    protected function __clone(){
        //disallow clone
    }
    public function getInstance()
    {
        if (self::$_instance === null) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}
class B extends A
{
    protected static $_instance = null;
}

$a = A::getInstance();
$b = B::getInstance();
var_dump($a === $b);


將__construct方法設為私人,可以保證這個類不被其他人執行個體化。但這種寫法一個顯而易見的問題是:代碼不能複用。比如我們在一個一個類繼承A:
複製代碼 代碼如下:

class B extends A
{
    protected static $_instance = null;
}

$a = A::getInstance();
$b = B::getInstance();
var_dump($a === $b);


上面的代碼會輸出:
複製代碼 代碼如下:

bool(true)

問題出在self上,self的引用是在類被定義時就決定的,也就是說,繼承了B的A,他的self引用仍然指向A。為瞭解決這個問題,在PHP 5.3中引入了後期靜態繫結的特性。簡單說是通過static關鍵字來訪問靜態方法或者變數,與self不同,static的引用是由運行時決定。於是簡單改寫一下我們的代碼,讓單例模式可以複用。
複製代碼 代碼如下:

class C
{
    protected static $_instance = null;
    protected function __construct()
    {

    }
    protected function __clone()
    {
        //disallow clone
    }
    public function getInstance()
    {
        if (static::$_instance === null) {
            static::$_instance = new static;
        }
        return static::$_instance;
    }
}
class D extends C
{
    protected static $_instance = null;
}
$c = C::getInstance();
$d = D::getInstance();
var_dump($c === $d);


以上代碼輸出:
複製代碼 代碼如下:

bool(false)

這樣,簡單的繼承並重新初始化$_instance變數就能實現單例模式。注意上面的方法只有在PHP 5.3中才能使用,對於之前版本的PHP,還是老老實實為每個單例類寫一個getInstance()方法吧。

需要提醒的是,PHP中單例模式雖然沒有像Java一樣的安全執行緒問題,但是對於有狀態的類,還是要小心的使用單例模式。單例模式的類會伴隨PHP啟動並執行整個生命週期,對於記憶體也是一種開銷。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.