php實(shí)現(xiàn)單例模式最安全的做法
來(lái)源:易賢網(wǎng) 閱讀:887 次 日期:2014-07-31 11:20:46
溫馨提示:易賢網(wǎng)小編為您整理了“php實(shí)現(xiàn)單例模式最安全的做法”,方便廣大網(wǎng)友查閱!

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

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

代碼如下:

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è)類不被其他人實(shí)例化。但這種寫法一個(gè)顯而易見(jiàn)的問(wèn)題是:代碼不能復(fù)用。比如我們?cè)谝粋€(gè)一個(gè)類繼承a:

代碼如下:

class b extends a

{

    protected static $_instance = null;

}

$a = a::getinstance();

$b = b::getinstance();

var_dump($a === $b);

上面的代碼會(huì)輸出:

代碼如下:

bool(true)

問(wèn)題出在self上,self的引用是在類被定義時(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)單改寫一下我們的代碼,讓單例模式可以復(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);

以上代碼輸出:

代碼如下:

bool(false)

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

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

更多信息請(qǐng)查看IT技術(shù)專欄

更多信息請(qǐng)查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機(jī)網(wǎng)站地址:php實(shí)現(xiàn)單例模式最安全的做法
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡(jiǎn)要咨詢 | 簡(jiǎn)要咨詢須知 | 加入群交流 | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)