面试手写单例模式怎么写

三私一公,私有的成员属性,私有的克隆,私有的构造函数,公共的静态调用方法。


<?PHP
class Example
 
{
 
//保存例实例在此属性中
 
private static $_instance;
 
  
 
//构造函数声明为private,防止直接创建对象
 
private function __construct()
 
{
 
echo 'I am Construceted';
 
}
 
  
 
//单例方法
 
public static function singleton()
 
{
 
if(!isset(self::$_instance))
 
{
 
$c=__CLASS__;
 
self::$_instance=new $c;
 
}
 
return self::$_instance;
 
}
 
  
 
//阻止用户复制对象实例
 
public function __clone()
 
{
 
trigger_error('Clone is not allow' ,E_USER_ERROR);
 
}
 
  
 
function test()
 
{
 
echo("test");
 
  
 
}
 
}
 
  
 
// 这个写法会出错,因为构造方法被声明为private
 
$test = new Example;
 
  
 
// 下面将得到Example类的单例对象
 
$test = Example::singleton();
 
$test->test();
 
  
 
// 复制对象将导致一个E_USER_ERROR.
 
$test_clone = clone $test;
 
?>

猜你喜欢

转载自blog.csdn.net/qq_43572631/article/details/86592383