class Test{
private static $_instance;
private function __construct(){
}
public function __clone(){
//防止被複制
trigger_error("Clone is not allow!",E_USER_ERROR);
}
public static function getInstance(){
if(!(self::$_instance instanceof self)){
//*****************
echo "測試地方一";
//*****************
self::$_instance = new self;
}
return self::$_instance;
}
public function test(){
echo "ok";
}
}
<?php
require_once(dirname(__FILE__).'/test.class.php');
$test = Test::getInstance();
$test->test();
$test2 = Test::getInstance();
$test2->test();
你會發現,也就是說,在實例化的過程當中,只輸出了一次"測試地方一"。而後第二次輸入ok的時候,表明已經跳過了實例化。因此,最終咱們的目的就達到了。單例模式其實就是這麼簡單。性能
單例模式的優勢:ui
- 在內存中只有一個對象,節省內存空間。
- 避免頻繁的建立銷燬對象,能夠提升性能。
- 避免對共享資源的多重佔用。
- 能夠全局訪問。
適用場景:因爲單例模式的以上優勢,因此是編程中用的比較多的一種設計模式。我總結了一下我所知道的適合使用單例模式的場景:設計