什么是单例模式
1.单例模式的定义:保证一个类只有一个实例,并提供一个访问它的全局访问点。
2.实例:
class Singleton
{
//创建静态私有的变量保存该类对象
static private $instance;
//防止使用new直接创建对象
private function __construct(){}
//防止使用clone克隆对象
private function __clone(){}
static public function getInstance()
{
//判断$instance是否是Singleton的对象,不是则创建
if (!self::$instance instanceof self) {
self::$instance = new self();
}
return self::$instance;
}
public function test()
{
echo "我是一个单例模式";
}
}
$sing = Singleton::getInstance();
$sing->test();
$sing2 = new Singleton();
Singleton::__construct() from invalid context in
$sing3 = clone $sing;
单例模式的实用意义
- 用于运行脚本,不用加载其他应用,节约资源。
- 用于测试代码,同上,节省资源。
- 用于保存全局配置参数,写在一个单例模式中,易于管理 。