這裏是Erich Gamma,Singleton模式的發明者之一,不得不說的是:
"I'm in favor of dropping Singleton. Its use is almost always a design smell"
因此,我建議使用Dependency Injection而不是單身人士。
在創建$ this之前創建助手實例。然後通過setter方法或通過構造函數將助手實例從外部設置到$ this實例。
作爲替代,創建一個知道如何通過名字來實例化助手並傳遞到$這個實例的助手經紀人
class HelperBroker
{
protected $helpers = array();
public function getHelper($name)
{
// check if we have a helper of this name already
if(!array_key_exists($name, $this->helpers)) {
// create helper and store for later subsequent calls
$this->helpers[$name] = new $name;
}
return $this->helpers[$name];
}
}
可以根據需要你懶負荷助手通過這種方式,將永遠無法獲得第二個例子,而不必使用Singleton。將代理的實例傳遞給需要使用助手的每個類。
實例與單個幫手
$helper = new Helper;
$someClass = new Something($helper);
和
class Something
{
protected $helper;
public function __construct($helper)
{
$this->helper = $helper;
}
public function useHelper()
{
$return = $this->helper->doSomethingHelpful();
}
}
在$東西,你現在可以直接存儲和訪問輔助實例。你不需要實例化任何東西。事實上,$某種東西甚至不必擔心助手是如何實例化的,因爲我們給它提供了一些它可能需要的東西。
現在,如果你想在$ SomeClass的使用超過一個幫手,你會使用相同的原則:
$helper1 = new Helper;
$helper2 = new OtherHelper;
$something = new Something($helper1, $helper2);
這份名單將得到相當長的您將更多的依賴前期。我們可能也不想實例化所有幫助者。這就是HelperBroker進場的地方。我們沒有將每個助手作爲準備好的實例傳遞給$ something,而是注入了一個知道如何創建助手的對象,並且跟蹤它們。
$broker = new HelperBroker;
$something = new Something($broker);
和
class Something
{
protected $helperBroker;
public function __construct($broker)
{
$this->helperBroker = $broker;
}
public function doSomethingHelpful()
{
$return = $this->getHelper('foo')->doSomethingHelpful();
}
public function doSomethingElse()
{
$return = $this->getHelper('bar')->doSomethingElse();
}
}
現售的東西可以得到它所需要的幫手,當它從代理需要他們。另外,任何需要訪問helper的類現在不再需要爲如何創建helper而煩惱,因爲這個邏輯被封裝在broker中。
$broker = new HelperBroker;
$something = new Something($broker);
$other = new Other($broker);
該券商還可以確保你只能有一個幫助程序實例,因爲當一個幫手被實例化,它存儲的經紀人內並在後續調用返回。這解決了你最初的問題,你不想恢復任何助手。它也不會強迫你的助手知道如何在全球化狀態下管理自己,比如Singleton。相反,你的幫手可以專注於他們的責任:幫助。這是乾淨,簡單和可重複使用的。
出於好奇:當你賦值'$ user = array()'時,getHelperInstance()怎麼被調用? – Gordon 2010-03-24 20:22:04
我的不好,用戶不是空的 – Rachel 2010-03-24 20:24:38
以及如何使用PHP4的可見性? PHP4中不存在可見性。嘗試打開命令提示符並輸入'php -v'來查看您使用的PHP版本。 – Gordon 2010-03-24 20:25:55