单例模式需要满足的条件:
1、private的构造函数
2、一个静态成员变量保存类的实例
3、一个访问这个实例的静态方法
<?php
class Single
{
/**
* 对象实例
* @var Single
*/
private static $instance = null;
/**
* 构造器私有化:防止从类外部实例化
*/
private function __construct()
{
echo '这里 new class <br>';
}
/**
* 克隆方法私有化:防止从外部克隆对象
*/
private function __clone()
{
}
/** 静态方法
* @return null|Single
*/
public static function getInstance()
{
// 检测当前类属性$instance是否已经保存了当前类的实例
if (self::$instance === null) {
// 没有,则创建当前类的实例
self::$instance = new self();
}
return self::$instance;
}
/**
* 测试方法
* @return string
*/
public function test()
{
return 'this is test';
}
}
调用测试
\Single::getInstance()->test();
\Single::getInstance()->test();
\Single::getInstance()->test();
运行结果只输出了一次new
这里 new class
说明使用单例模式,只需要实例化一次,不需要每次都执行new操作,极大降低了资源的耗费。
加我微信公众号【皮蛋馅儿】,一起学习哦~
网友评论