單例模式是一種比較常用的設計模式,在很多框架中可以看到它的身影。通過單例模式可以確保類只有一個實例化,從而方便對實例個數的控制并節約系統資源。
?phpuse /Exception;html' target='_blank'>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( Clone is not allowed ! }
一個系統中可能會多次使用到單例模式,為了更加方便的創建,可以試著建立一個通用的抽象:
// SingletonFacotry.php ?phpuse /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( Clone is not allowed ! }
// A.php ?phpclass 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教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答