0
点赞
收藏
分享

微信扫一扫

php 单例模式

IT程序员 2023-07-29 阅读 65

1,单例模式,属于创建设计模式,简单来说就是一个类只能有一个实例化对象,并提供一个当前类的全局唯一可访问入口;

2,例子


<?php
 
class Singleton
{
    private static $instance = null;
 
    // 禁止被实例化
    private function __construct()
    {
 
    }
 
    // 禁止clone
    private function __clone()
    {
 
    }
        //  实例化自己并保存到$instance中,已实例化则直接调用
    public static function getInstance(): object
    {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
 
    
}
 
// 两次调用返回同一个实例
$single1 = Singleton::getInstance();
$single2 = Singleton::getInstance();
 

 可继承的单例模式:

abstract class Singleton
{

    // 受保护的构造函数,确保不能通过 new 关键字直接实例化对象
    protected function __construct()
    {
        // 初始化操作
    }

    // 防止对象被复制
    protected function __clone()
    {
        throw new Exception("Singleton instance cannot be cloned.");
    }

    // 防止对象被序列化
    protected function __wakeup()
    {
        throw new Exception("Singleton instance cannot be serialized.");
    }

    // 获取实例的静态方法
    public static function getInstance()
    {
        if (!static::$instance) {
            static::$instance = new static();
        }
        return static::$instance;
    }
    // 其他业务方法
}

class SubSingleton extends Singleton
{
    protected static $instance=null;
    // 添加其他额外的功能或覆盖父类的方法
}

class Sub extends Singleton
{
    protected static $instance=null;
    // 添加其他额外的功能或覆盖父类的方法
}

//$singleton1和$singleton2 是同一个实例
$sub1 = Sub::getInstance();
$sub2 = Sub::getInstance();
var_dump($sub1);//object(Sub)#1 (0) { }
var_dump($sub2);//object(Sub)#1 (0) { }

//$subSingleton1 和subSingleton2是同一个实例
$subSingleton1 = SubSingleton::getInstance();
$subSingleton2 = SubSingleton::getInstance();
var_dump($subSingleton1);//object(SubSingleton)#2
var_dump($subSingleton2);//object(SubSingleton)#2
举报

相关推荐

0 条评论