[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
单例模式的定义
确保某一个类只有一个实例,不能重复实例,只能它自己实例化,而且向整个系统提供这个实例。
解决的问题
即一个类只被实例化一次,当其他人对其再次实例化时,返回第一次实例化的对象,可以避免大量的 new 操作,减少资源的消耗。
原则:四步走,三私一公
* 私有化静态属性
* 私有化构造方法
* 私有化克隆方法
* 公有化静态方法
封装背景
当项目中有多个单例类,每新建一个类,都得做三私一公的定义,就显得有些做重复工作了,不仅仅浪费时间浪费精力,而且代码臃肿且难维护,有没有 更优雅 的写法呢?
Trait来封装单例
php从以前到现在一直都是单继承的语言,无法同时从两个基类中继承属性和方法,为了解决这个问题,php出了Trait这个特性
用法: 通过在类中使用 use 关键字,声明要组合的 Trait 名称,具体的 Trait 的声明使用 Trait关键词,Trait不能被实例化。
Code示例
创建一个Trait
<?php /** * Trait Singleton 单例模式 */ Trait Singleton { private static $instance
= null; private function __construct() { parent::__construct(); // 私有化构造方法 }
private function __clone() { // 私有化克隆方法 } public function __sleep() {
//重写__sleep方法,将返回置空,防止序列化反序列化获得新的对象 return []; } public static function
getInstance() { if (!isset(self::$instance)) { self::$instance = new
static();//这里不能new self(),self和static区别 } return self::$instance; } }
多继承用法
其他类只用在代码中 use Singleton; ,即可继承单例了 <?php /** * Desc: 业务类1 继承实例 */ class YieWu1
{ use Singleton; // 关键一行代码 public function getInfo(){ // 业务代码 } } <?php /** *
Desc: 业务类2 继承实例 */ class YieWu2 { use Singleton; // 关键一行代码 public function
getInfo(){ // 业务代码 } }
实列调用
YieWu1::getInstance()->getInfo(); YieWu2::getInstance()->getInfo();