首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 物件導向程式設計 (OOP) 學習筆記 (三) - 單例模式與工廠模式

     編輯:PHP 綜合知識

設計模式是軟體架構的基石。本文介紹兩種最常用的創建型模式:單例模式 確保類別僅有一個實例;簡單工廠模式 封裝物件建立邏輯,降低耦合。

單例模式

四大要素:

  1. private 建構子:防止外部 new 實例化。
  2. 靜態私有變數 $_instance:儲存唯一實例。
  3. 靜態公開方法 getInstance():提供全域存取點。
  4. 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.

比較與總結

特性單例模式簡單工廠模式
目的全域唯一實例集中建立邏輯,解耦使用者與具體類別
關鍵結構私有建構子 + 靜態實例變數靜態工廠方法 + 介面/抽象類別
適用場景資料庫連線、日誌器、設定管理多型物件建立、外掛系統、策略切換
擴充性較難擴充 (需修改類別)易擴充 (新增類別即可,工廠可配合反射自動發現)

進階提示

  • 單例在單元測試中難以模擬,現代框架常改用依賴注入 (DI) 容器管理共享實例。
  • 工廠模式可延伸為工廠方法模式、抽象工廠模式,應對更複雜的物件圖建構。
  • PHP 5.4+ 可使用 trait 實作可復用的單例基礎邏輯。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved