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

PHP 五大經典設計模式實作指南:工廠、單例、觀察者、策略、裝飾器

     編輯:PHP 綜合知識

設計模式價值

提供通用詞彙溝通複雜結構、促進鬆耦合、提高可測試性與可維護性。非 Java 專屬,PHP 同樣受益。

1. 工廠模式 - 封裝物件建立

name; }
}

class UserFactory {
    public static function create(int $id): UserInterface {
        // 可依 id 從 DB/快取/外部 API 取得資料
        return new User("User_$id");
    }
}

// 使用
$user = UserFactory::create(1);
echo $user->getName(); // User_1

優點:呼叫端不依賴具體類別,易於替換實作 (測試用 Mock、不同儲存後端)。

2. 單例模式 - 全域唯一實例 (慎用)

pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
    }
    
    public static function getInstance(): self {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function getConnection(): PDO { return $this->pdo; }
    
    // 防止複製/序列化
    private function __clone() {}
    public function __wakeup() { throw new Exception("Cannot unserialize singleton"); }
}

// 使用
$pdo = Database::getInstance()->getConnection();

⚠️ 缺點:全域狀態、難以測試、隱性依賴。現代偏好 依賴注入 (DI) + 容器管理生命週期。

3. 觀察者模式 - 事件驅動解耦

listeners[$event][] = $listener;
    }
    
    public function dispatch(string $event, mixed $data = null): void {
        foreach ($this->listeners[$event] ?? [] as $listener) {
            $listener->handle($event, $data);
        }
    }
}

// 具體監聽器
class EmailNotifier implements EventListener {
    public function handle(string $event, mixed $data): void {
        if ($event === 'user.registered') {
            mail($data['email'], 'Welcome', 'Hi ' . $data['name']);
        }
    }
}

class LogListener implements EventListener {
    public function handle(string $event, mixed $data): void {
        error_log("[$event] " . json_encode($data));
    }
}

// 使用
$dispatcher = new EventDispatcher();
$dispatcher->subscribe('user.registered', new EmailNotifier());
$dispatcher->subscribe('user.registered', new LogListener());

$dispatcher->dispatch('user.registered', ['name' => 'John', 'email' => 'john@example.com']);

// 現代框架整合:Laravel Events、Symfony EventDispatcher、PSR-14

4. 策略模式 - 演算法可互換

strategy->pay($amount);
    }
}

// 運行時決定策略
$method = $_POST['payment_method'] ?? 'credit';
$strategy = match ($method) {
    'paypal' => new PayPalPayment(),
    'crypto' => new CryptoPayment(),
    default => new CreditCardPayment(),
};

$order = new Order($strategy);
$order->checkout(99.99);

5. 裝飾器模式 - 動態擴展行為

wrapped->send($message);
    }
}

class EmailDecorator extends NotifierDecorator {
    public function send(string $message): void {
        parent::send($message);
        mail('admin@example.com', 'Notification', $message);
    }
}

class SlackDecorator extends NotifierDecorator {
    public function send(string $message): void {
        parent::send($message);
        // 發送至 Slack Webhook
    }
}

// 組合使用
$notifier = new SlackDecorator(new EmailDecorator(new BaseNotifier()));
$notifier->send('Server CPU > 90%');

現代 PHP 應用建議

  • 搭配 PSR-11 容器 (PHP-DI、Symfony DI、Laravel Container) 管理依賴
  • 使用 屬性 (PHP 8+) 標記服務、事件監聽器
  • 領域事件 + 事件總線 替代手動觀察者註冊
  • 策略模式配合 Enum 定義支援類型
  • 避免過度設計:YAGNI、KISS、SOLID 原則指導
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved