只能有一個實例。php
必須自行建立這個實例。redis
必須給其餘對象提供這一實例數據庫
應用程序與數據庫打交道的場景,在一個應用中會存在大量的數據庫操做,針對數據庫句柄鏈接數據庫的行爲,使用單例模式能夠避免大量的new操做。由於每一次new操做都會消耗系統和內存的資源。設計模式
WEB開發中的全局配置類文件等均可以使用單例模式。memcached
redis示例、memcached示例等等。相似的場景不少、一個系統只要是有且只須要一個實例的類均可以考慮此設計模式。this
<?php /** *簡而言之、一個站點有也只能有一個實例對象的類均可以使用單例模式來設計。如下只是平時簡單的單例寫法示例。僅供參考! */ class Conf { //爲了保證該單一實例不被外部修改,使用private static private $_instance = null; private $_settings = []; //對外公開的獲取單例示例的方法 static function getInstance() { //首次反問時內部建立一個示例、並保存於靜態變量中 if (self::$_instance == null) { self::$_instance = new Conf(); } //返回conf的實例 return self::$_instance; } //爲了不外面用 new 和 clone來建立而外的實例。此處建立一個私有的 construct 和 clone private function __construct() {} private function __clone() {} //設置配置值 function set($index, $value) { //此處還能夠處理不少異常處理,這裏很少說 $this->_settings[$index] = $value; } //獲取配置值 function get($index) { //此處還能夠處理不少異常處理,這裏很少說 return isset($this->_settings[$index]) ? $this->_settings[$index] : ''; } }