設計模式是軟體架構的基石。本文介紹兩種最常用的創建型模式:單例模式 確保類別僅有一個實例;簡單工廠模式 封裝物件建立邏輯,降低耦合。
四大要素:
private 建構子:防止外部 new 實例化。$_instance:儲存唯一實例。getInstance():提供全域存取點。private __clone():防止複製。class Singleton {
private static $_instance = null;
private function __construct() {
// 初始化邏輯
}
private function __clone() {
// 禁止複製
}
public static function getInstance() {
if (!(self::$_instance instanceof self)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function sayHi() {
echo "Hi boy!";
}
}
// 使用
$app = Singleton::getInstance();
$app->sayHi(); // 輸出: Hi boy!
適用場景:大量實作同一介面的類別,需根據條件動態建立實例。
interface ProductInterface {
public function showProductInfo();
}
class ProductA implements ProductInterface {
public function showProductInfo() { echo 'This is product A.'; }
}
class ProductB implements ProductInterface {
public function showProductInfo() { echo 'This is product B.'; }
}
class ProductFactory {
public static function factory($type) {
$className = 'Product' . strtoupper($type);
if (class_exists($className)) {
return new $className();
}
throw new Exception("Unknown product type: $type");
}
}
// 使用
$x = ProductFactory::factory('A');
$x->showProductInfo(); // This is product A.
$o = ProductFactory::factory('B');
$o->showProductInfo(); // This is product B.
| 特性 | 單例模式 | 簡單工廠模式 |
|---|---|---|
| 目的 | 全域唯一實例 | 集中建立邏輯,解耦使用者與具體類別 |
| 關鍵結構 | 私有建構子 + 靜態實例變數 | 靜態工廠方法 + 介面/抽象類別 |
| 適用場景 | 資料庫連線、日誌器、設定管理 | 多型物件建立、外掛系統、策略切換 |
| 擴充性 | 較難擴充 (需修改類別) | 易擴充 (新增類別即可,工廠可配合反射自動發現) |
trait 實作可復用的單例基礎邏輯。