单件模式又称单例模式,是一种用于确保整个应用程序中只有一个类实例且这个实例所占资源在整个应用程序中是共享的程序设计方法。
class Singleton
{
/**
* 声明一个静态私有变量来保存该类的唯一实例
* @var Singleton
*/
static private $_instance;
/**
* 私有化构造函数,防止外部使用new创建对象
* @throws Exception
*/
private function __construct()
{
}
/**
* 获取本类实例的唯一方法
* @return Singleton
*/
static public function getInstance()
{
if (self::$_instance === null) {
self::$_instance = new Singleton();
}
return self::$_instance;
}
/**
* 防止使用clone方法进行对象的克隆
* @throws Exception
*/
public function __clone()
{
throw new Exception(‘这是一个单例,不能被克隆。‘);
}
/**
* 防止对象被序列化后进行反序列化获得新对象
*/
public function __sleep()
{
throw new Exception(‘这是一个单例,不能被序列化。‘);
}
public function test()
{
echo ‘单例模式‘;
}
}
使用:
# ---------------------------------------- 正确 ---------------------------------------- $instance = Singleton::getInstance(); $instance->test(); //输出:单例模式 # ---------------------------------------- 错误 ---------------------------------------- $instance = new Singleton(); //输出:Fatal error: Uncaught Error: Call to private Singleton::__construct() from invalid context # ---------------------------------------- 错误 ---------------------------------------- $instance = Singleton::getInstance(); $instanceNew = clone $instance; //输出:Fatal error: Uncaught Exception: 这是一个单例,不能被克隆。 # ---------------------------------------- 错误 ---------------------------------------- $instance = Singleton::getInstance(); $serialize = serialize($instance); //输出:Fatal error: Uncaught Exception: 这是一个单例,不能被序列化。 $instanceNew = unserialize($serialize);
单件模式在这里就说完了,是不是觉得很简单,觉得设计模式也不过如此。哈^-^……告诉你,好戏还在后头,下一篇我们将讲解PHP设计模式之路-工厂模式。
敬请期待。。。
PHP设计模式之路-单件模式(Singleton Pattern)
原文:https://www.cnblogs.com/keng333/p/14306617.html