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()
    {
    }
}
相關文章
相關標籤/搜索