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中文网其他相关文章!