第1关:饿汉式
<?php
class Singleton
{
public $name;
/********** Begin **********/
/********** 1. 单例模式的类只能有一个实例,并由类自己创建(此处略) **********/
public static $instance;
/********** 2. 构造函数必须为私有 **********/
private function __construct(){
}
/********** 3. 克隆函数必须为私有 **********/
private function __clone(){
}
/********** 4. 必须提供一个静态的访问方法 **********/
public static function getInstance()
{
if(!(self::$instance instanceof self)){
self::$instance = new self();
}
return self::$instance;
}
/********** End **********/
}
第2关:懒汉式
<?php
class Singleton
{
public $name;
/********** Begin **********/
/********** 1. 单例模式的类只能有一个实例 **********/
private static $instance;
/********** 2. 构造函数必须为私有 **********/
private function __construct()
{
}
/********** 3. 克隆函数必须为私有 **********/
private function __clone()
{
}
/********** 4. 必须提供一个静态的访问方法,并在每次调用时判断实例是否存在 **********/
public static function getInstance()
{
if (!(self::$instance instanceof self)){
self::$instance = new self();
}
return self::$instance;
}
/********** End **********/
}
第3关:封装-通用单例基类
<?php
abstract class Singleton
{
public $name;
/********** Begin **********/
/********** 1. 单例模式的类只能有一个实例 **********/
protected static $instance;
/********** 2. 构造函数必须为私有 **********/
private function __construct()
{
}
/********** 3. 克隆函数需要为protected,会被子类继承但不允许子类重写 **********/
protected function __clone()
{
}
/********** 4. 必须提供一个静态的访问方法,并在每次调用时判断实例是否存在,且不允许子类重写 **********/
public final function getInstance()
{
if (!self::$instance instanceof self) {
self::$instance = new static();
}
return self::$instance;
}
/********** End **********/
}