PHP 单例模式

单例模式主要用于解决一个全局使用的类频繁地建立与销毁的问题,能够节省系统资源。特征是将构造函数设置为私有,主要用于数据库链接、系统产生惟一序列号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()
    {
    }
}
相关文章
相关标签/搜索