PHP,特別是 PHP 中的屬性、枚舉和唯讀屬性等現代功能,非常適合實現設計模式。以下是每個軟體工程師都應該了解的五個基本模式。
確保一個類別只有一個實例。
final class Config { private static ?Config $instance = null; private function __construct(public readonly array $settings) {} public static function getInstance(): Config { return self::$instance ??= new Config(['env' => 'production']); } } // Usage $config = Config::getInstance(); echo $config->settings['env']; // Output: production
集中物件建立邏輯。
class DatabaseFactory { public static function create(string $type): Database { return match ($type) { 'mysql' => new MySQLDatabase(), 'postgres' => new PostgresDatabase(), default => throw new InvalidArgumentException("Unknown database type"), }; } } interface Database { public function connect(): void; } class MySQLDatabase implements Database { public function connect() { echo "MySQL connected"; } } class PostgresDatabase implements Database { public function connect() { echo "Postgres connected"; } } // Usage $db = DatabaseFactory::create('mysql'); $db->connect(); // Output: MySQL connected
通知多個物件有關狀態變更的資訊。
class Event { private array $listeners = []; public function attach(callable $listener): void { $this->listeners[] = $listener; } public function trigger(string $data): void { foreach ($this->listeners as $listener) $listener($data); } } // Usage $event = new Event(); $event->attach(fn($data) => print "Listener 1: $data\n"); $event->attach(fn($data) => print "Listener 2: $data\n"); $event->trigger("Event triggered"); // Output: // Listener 1: Event triggered // Listener 2: Event triggered
動態新增行為給物件。
interface Text { public function render(): string; } class PlainText implements Text { public function __construct(private string $text) {} public function render(): string { return $this->text; } } class BoldText implements Text { public function __construct(private Text $text) {} public function render(): string { return "<b>" . $this->text->render() . "</b>"; } } // Usage $text = new BoldText(new PlainText("Hello, World!")); echo $text->render(); // Output: <b>Hello, World!</b>
運行時在演算法之間切換。
interface PaymentStrategy { public function pay(float $amount): void; } class CreditCardPayment implements PaymentStrategy { public function pay(float $amount): void { echo "Paid $amount with Credit Card\n"; } } class PayPalPayment implements PaymentStrategy { public function pay(float $amount): void { echo "Paid $amount via PayPal\n"; } } class PaymentProcessor { public function __construct(private PaymentStrategy $strategy) {} public function execute(float $amount): void { $this->strategy->pay($amount); } } // Usage $processor = new PaymentProcessor(new PayPalPayment()); $processor->execute(100.00); // Output: Paid 100 via PayPal
這些模式解決了現實世界的問題,是編寫可維護和可擴展的應用程式的基礎。
哪種模式與您目前的專案產生共鳴?快來評論裡討論吧! ?
以上是每個軟體工程師都應該知道的頂級設計模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!