關於原廠模式的有關問題

來源:互聯網
上載者:User
關於原廠模式的問題
Example #1 調用Factory 方法(帶參數)
class Example
{
// The parameterized factory method
public static function factory($type)
{
if (include_once 'Drivers/' . $type . '.php') {
$classname = 'Driver_' . $type;
return new $classname;
} else {
throw new Exception ('Driver not found');
}
}
}
?>
按上面的方式可以動態載入drivers。如果Example類是一個資料庫抽象類別,那麼 可以這樣來產生MySQL和 SQLite驅動對象:
// Load a MySQL Driver
$mysql = Example::factory('MySQL');

// Load a SQLite Driver
$sqlite = Example::factory('SQLite');
?>


原文地址:
http://www.php.net/manual/zh/language.oop5.patterns.php


我想瞭解,這種模式有什麼作用

而且,包含檔案的類名前面必須被加上“Driver_" 這個首碼,豈不是很不方便而且有限制性?

這樣到底實現了什麼動態?

------解決方案--------------------
Driver_MySQL 和 Driver_SQLite 實現同一介面,那麼你的程式就不必關心資料庫是哪種,方便了將來更換資料庫系統(當然SQL語句上可能還存在問題)
至於為什麼 Driver_ 當首碼,那是擔心會發生類重名,或者是出於方便管理的目的才這樣設的。
------解決方案--------------------
這種模式有什麼作用...
抽象高於實現,原廠模式在抽象類別型建立對象時.使用特定的類來實現.

driver 你不覺得加個首碼很醒目麼,要不變數名都用 $a,$b,$c 你覺得能弄明白是做啥的?猜你都沒法猜的不是...
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.