PHP 单例模式

单例模式主要用于解决一个全局使用的类频繁地创建与销毁的问题,可以节省系统资源。特征是将构造函数设置为私有,主要用于数据库连接、系统产生唯一序列号

<?php


namespace DesignModel;


/**
 * 单例模式
 * Class SingletonClass
 * @package DesignModel
 */
final class SingletonClass
{
    /**
     * @var SingletonClass
     */
    private static $instance;

    /**
     * 不能外部实例化,只能通过 SingletonClass::getInstance() 实现
     * SingletonClass constructor.
     */
    private function __construct()
    {
    }

    /**
     * 通过懒加载获得实例
     * @return SingletonClass
     */
    public static function getInstance(): SingletonClass
    {
        if (null === static::$instance) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    /**
     * 防止实例被克隆
     */
    private function __clone()
    {
    }

    /**
     * 防止反序列化
     */
    private function __wakeup()
    {
    }
}
原文地址:https://www.cnblogs.com/it-abel/p/11070368.html