單例模式 :生成一個且只生成一個對象實例
<?php
class Preferences
{
private $props = array();
//無法在類外部訪問
private static $instance;
//構(gòu)造函數(shù)私有 無法直接new
private function __construct()
{
}
//此處為公共入口 靜態(tài)方法可以訪問靜態(tài)屬性,無法使用類的實例
public static function getInstance()
{
if (empty(self::$instance)) {
self::$instance = new Preferences();
}
return self::$instance;
}
public function setProperty($key, $val)
{
$this->props[$key] = $val;
}
public function getProperty($key)
{
return $this->props[$key];
}
}
$pref = Preferences::getInstance();
$pref->setProperty("name", "matt");
unset($pref); // remove the reference
$pref2 = Preferences::getInstance();
print $pref2->getProperty("name") . "\n"; // demonstrate value is not lost
執(zhí)行以上代碼后,可得
matt
全局變量不受保護,但不可避免,我們需要一個提供所有類都能訪問某個對象存在
問題:
Preferences對象應(yīng)該可以被系統(tǒng)中的任何對象使用
Preferences對象不應(yīng)該被存儲在會被覆寫的全局變量中
系統(tǒng)中不應(yīng)超過一個preferences對象.
也就是說Y對象可以設(shè)置preferences對象個一個屬性,而Z對象不需要其他對象就可以直接獲取該屬性的值
結(jié)果:適度使用單例模式,可以不用傳遞那些不必要的對象.是對全局變量一種改進