提供通用詞彙溝通複雜結構、促進鬆耦合、提高可測試性與可維護性。非 Java 專屬,PHP 同樣受益。
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、不同儲存後端)。
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) + 容器管理生命週期。
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
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);
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%');