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
- 在内存中只有一个对象,节省内存空间。
- 避免频繁的建立销毁对象,能够提升性能。
- 避免对共享资源的多重占用。
- 能够全局访问。
适用场景:因为单例模式的以上优势,因此是编程中用的比较多的一种设计模式。我总结了一下我所知道的适合使用单例模式的场景:设计