亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

PHP實(shí)現(xiàn)單例模式最安全的做法

 更新時(shí)間:2014年06月13日 10:53:03   投稿:junjie  
這篇文章主要介紹了PHP實(shí)現(xiàn)單例模式最安全的做法,適用PHP5.3以上版本,采用了最好的做法,需要的朋友可以參考下

作為一種常用的設(shè)計(jì)模式,單例模式被廣泛的使用。那么如何設(shè)計(jì)一個(gè)單例才是最好的呢?

通常我們會(huì)這么寫(xiě),網(wǎng)上能搜到的例子也大部分是這樣:

復(fù)制代碼 代碼如下:

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方法設(shè)為私有,可以保證這個(gè)類(lèi)不被其他人實(shí)例化。但這種寫(xiě)法一個(gè)顯而易見(jiàn)的問(wèn)題是:代碼不能復(fù)用。比如我們?cè)谝粋€(gè)一個(gè)類(lèi)繼承A:
復(fù)制代碼 代碼如下:

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

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


上面的代碼會(huì)輸出:
復(fù)制代碼 代碼如下:

bool(true)

問(wèn)題出在self上,self的引用是在類(lèi)被定義時(shí)就決定的,也就是說(shuō),繼承了B的A,他的self引用仍然指向A。為了解決這個(gè)問(wèn)題,在PHP 5.3中引入了后期靜態(tài)綁定的特性。簡(jiǎn)單說(shuō)是通過(guò)static關(guān)鍵字來(lái)訪問(wèn)靜態(tài)的方法或者變量,與self不同,static的引用是由運(yùn)行時(shí)決定。于是簡(jiǎn)單改寫(xiě)一下我們的代碼,讓單例模式可以復(fù)用。
復(fù)制代碼 代碼如下:

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);


以上代碼輸出:
復(fù)制代碼 代碼如下:

bool(false)

這樣,簡(jiǎn)單的繼承并重新初始化$_instance變量就能實(shí)現(xiàn)單例模式。注意上面的方法只有在PHP 5.3中才能使用,對(duì)于之前版本的PHP,還是老老實(shí)實(shí)為每個(gè)單例類(lèi)寫(xiě)一個(gè)getInstance()方法吧。

需要提醒的是,PHP中單例模式雖然沒(méi)有像Java一樣的線程安全問(wèn)題,但是對(duì)于有狀態(tài)的類(lèi),還是要小心的使用單例模式。單例模式的類(lèi)會(huì)伴隨PHP運(yùn)行的整個(gè)生命周期,對(duì)于內(nèi)存也是一種開(kāi)銷(xiāo)。

相關(guān)文章

最新評(píng)論