您现在的位置是:网站首页 > 心得笔记
单例模式
简介应用场景:数据库连接这种比较耗费资源的操作,我们希望整个应用只实例化一个
结构:四私一公
私有构造方法:防止使用new创建多个实例
私有克隆方法:防止clone多个实例
私有重建方法:防止反序列化
私有静态属性:防止时间访问存储实例的属性
普通类 class DB1 { public static $instance = null; public static function getInstance() { if (self::$instance == null) { static::$instance = new static(); } return static::$instance; } public function __construct() { } public fucntion __clone() { } public function __wakeup() { } } $db1 = new DB1(); $db2 = new DB1(); $db3 = clone $db2; $db4 = DB1::getInstance(); $db5 = unserialize(serialize($db4)); 单例 class DB2 { private static $instance = null; public static function getInstance() { if (self::$instance == null) { self::$instance = new static(); } return self::$instance; } /** * 防止使用 new 创建多个实例 * * DB2 constructor. */ private function __construct() { } /** * 防止 clone 多个实例 */ private function __clone() { } /** * 防止反序列化 */ private function __wakeup() { } } $db6 = DB2::getInstance(); $db7 = DB2::getInstance(); 运行代码我们可以看到; 普通类DB1的句柄每个都是不一样的; 一共5个实例; 而单例这两个的句柄都是 27 ; 一直是一个实例; ------------------------------------------ THE END ------------------------------------------
上一篇:php函数作用于数组中的每个值
下一篇:工厂模式