首頁  >  文章  >  後端開發  >  php單例模式的解說(程式碼範例)

php單例模式的解說(程式碼範例)

不言
不言轉載
2018-10-24 17:30:032827瀏覽

這篇文章帶給大家的內容是關於php單例模式的講解(程式碼範例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

單例模式是一種比較常用的設計模式,在許多框架中可以看到它的身影。透過單例模式可以確保類別只有一個實例化,從而方便對實例個數的控制並節約系統資源。

<?php

use \Exception;

class Singleton
{
    /**
     * 对象实例
     * @var object
     /
    public static $instance;
    
    /**
     * 获取实例化对象
     /
    public static function getInstance()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        
        return self::$instance;
    }
    
    /**
     * 禁止对象直接在外部实例
     /
    private function __construct(){}
    
    /**
     * 防止克隆操作
     /
    final public function __clone()
    {
        throw new Exception(&#39;Clone is not allowed !&#39;);
    }
}

一個系統中可能會多次使用到單例模式,為了更方便的創建,可以試著建立一個通用的抽象:

// SingletonFacotry.php
<?php

use \Exception;

abstract class SingletonFacotry
{
    /**
     * 对象实例数组
     * @var array
     /
    protected static $instance = [];
    
    /**
     * 获取实例化对象
     /
    public static function getInstance()
    {
        $callClass = static::getInstanceAccessor();
        if (!array_key_exists($callClass, self::$instance)) {
            self::$instance[$callClass] = new $callClass();
        }
        
        return self::$instance[$callClass];
    }
    
    abstract protected static function getInstanceAccessor();
    
    /**
     * 禁止对象直接在外部实例
     /
    protected function __construct(){}   
    
    /**
     * 防止克隆操作
     /
    final public function __clone()
    {
         throw new Exception(&#39;Clone is not allowed !&#39;);
    }
}
// A.php 
<?php

class A extends SingletonFactory
{
    public $num = 0;

    protected static function getInstanceAccessor()
    {
        return A::class;
    }
}

$obj1 = A::getInstance();
$obj1->num++;
var_dump($obj1->num); // 1
$obj2 = A::getInstance();
$obj2->num++;
var_dump($obj2->num); // 2

#

以上是php單例模式的解說(程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除