创建型设计模式 - 单例 Singleton
作者:菜皮日记
- 2023-09-08 北京
本文字数:649 字
阅读完需:约 2 分钟
简介
全局共用一个对象,好处是对象只实例化一次,减少资源占用,例如可以用在一些外部资源的连接上,可以减少系统持有连接资源的开销。
角色
单例类
返回本类的唯一一个实例
代码
class Singleton{ private static $instances = [];
protected function __construct() { }
protected function __clone() { }
public function __wakeup() { throw new \Exception("Cannot unserialize a singleton."); }
public static function getInstance(): Singleton { $cls = static::class; if (!isset(self::$instances[$cls])) { self::$instances[$cls] = new static(); }
return self::$instances[$cls]; }
public function someBusinessLogic() { // ... }}
function clientCode(){ $s1 = Singleton::getInstance(); $s2 = Singleton::getInstance(); if ($s1 === $s2) { echo "Singleton works, both variables contain the same instance."; } else { echo "Singleton failed, variables contain different instances."; }}
clientCode();
复制代码
output:
Singleton works, both variables contain the same instance.
复制代码
划线
评论
复制
发布于: 刚刚阅读数: 6
菜皮日记
关注
全干程序员 2018-08-08 加入
还未添加个人简介










评论