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

PHP 面向對象(OOP)學習筆記(三):單例模式與工廠模式實戰

     編輯:PHP 相關知識

設計模式是軟件工程基石。本文實現兩大創建型模式:

單例模式

確保全局唯一實例,四要素:

  1. 私有構造函數防外部 new
  2. 靜態私有屬性保存實例
  3. 公共靜態 GetInstance() 獲取實例
  4. 私有 __clone() 防克隆
class Singleton {
    private static $_instance;
    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!"; }
}
Singleton::GetInstance()->sayHi();

簡單工廠模式

集中實例化邏輯,配合接口實現多態:

interface ProductInterface { public function showInfo(); }
class ProductA implements ProductInterface { public function showInfo() { echo 'A'; } }
class ProductB implements ProductInterface { public function showInfo() { echo 'B'; } }
class Factory {
    public static function create($type) {
        $class = 'Product' . strtoupper($type);
        if (class_exists($class)) return new $class();
        throw new Exception("Invalid type");
    }
}
Factory::create('A')->showInfo(); // A

小結

單例保證唯一性,工廠解耦創建邏輯,配合接口實現「面向抽象編程」。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved