2.4. 单例模式(Singleton)
定义
- 只能通过一种方式获得实例
- 这个实例是
"缓存"
的
<?php
class AuthService
{
private static $instance; //本类
public static function getInstance()
{
if (null === static::$instance)
static::$instance = new static();
return static::$instance;
}
//这也算单例了
protected $user;
public function getUser()
{
if( $this->user == null)
$this->user = ["id" => 1,'nickname' => 'hello'];
return $this->user;
}
//你能保证没有有憨逼会用其他方式调用这个类 后续一堆private限制可以不写 麻烦
private function __construct() {}
}
结论
这个代码严格上并不算单例,因为他不满足 只能通过一种方式获得实例
。
(现在这个代码通过clone
extends
unserialize
new
都可以获得实例)
但也算是单例,因为他满足 "缓存"
。
比如:工厂模式
队友
不想通过工厂创建, 直接new 对象,你能咋办?
因此,这些限定代码,就是为了防止队友
搞破坏,我一般都不加这些限定的,单人开发。