php 单例模式

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

2,例子


 可继承的单例模式:

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

你可能感兴趣的:(php,单例模式,创建设计模式)