单例模式 - Single Instance

单例模式指的是在应用程序的范围内只对指定的类创建一个实例。

单例模式包含的对象只有一个,就是单例本身。

使用单例模式的类通常拥有一个私有构造函数和一个公有克隆函数,确保用户无法通过创建对象或克隆的方式对其进行实例化。

除些之外,该模式中还包含一个静态私有成员变量 $instance 与静态方法 getInstance。 

getInstance 方法负责对其本身实例化,然后将这个对象存储在 $instance 静态成员变量中,以确保只有一个实例被创建。

<?php
/**
 * SingelTon 单例模式
 * LSB 延迟静态绑定
 */

class Singleton
{
	protected static $_instance = null;

	private function __construct()
	{
	}

	public function __clone()
	{
		trigger_error("Clone is not allowed, ", E_USER_ERROR);
	}

	public static function getInstance()
	{
		if (null !== static::$_instance) {
			return static::$_instance;
		}
		static::$_instance = new static;
		return static::$_instance;
	}
}

/**
 * MYSQL实例
 */
class Mysql extends Singleton
{
	protected static $_instance = 'Mysql';
}

/**
 * MSSQL实例
 */
class Mssql extends Singleton
{
	protected static $_instance = 'Mssql';
}

var_dump(Singleton::getInstance());
var_dump(Mysql::getInstance());
var_dump(Mssql::getInstance());


class Cache
{
	private static $instance = null;

	private function __construct()
	{

	}

	public static function getInstance()
	{
		if (!self::$instance) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	public function __clone()
	{
		trigger_error("Clone is not allowed, ", E_USER_ERROR);
	}
}

$cache = Cache::getInstance();
$cache2 = clone $cache;
var_dump($cache);
var_dump($cache2);


执行结果:

object(Singleton)#1 (0) {
}
string(5) "Mysql"
string(5) "Mssql"
<br />
<b>Fatal error</b>:  Clone is not allowed,  in <b>D:\www\demo\phper\Singleton.php</b> on line <b>71</b><br />


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值