PHP 設計模式實現了行為型程式設計原則,透過定義明確的行為來創建可重複和鬆散耦合的程式碼。具體模式包括:觀察者模式:定義訂閱-發布關係,便於物件監聽和回應事件。策略模式:允許在不同演算法間切換,根據需要執行不同的操作。命令模式:將請求封裝成對象,以參數化方式執行它們。
行為型程式設計透過定義明確定義的行為,創造可重複且鬆散耦合的程式碼。 PHP 提供了許多設計模式來實現行為型編程,讓我們來探索它們。
觀察者模式定義訂閱-發布關係,其中一個物件(主題)可以發出通知,而其他物件(觀察者)可以對其進行監聽。
interface Observer { public function update($subject); } class ConcreteObserver1 implements Observer { public function update($subject) { echo "ConcreteObserver1 received update from $subject\n"; } } class ConcreteObserver2 implements Observer { public function update($subject) { echo "ConcreteObserver2 received update from $subject\n"; } } class Subject { private $observers = []; public function attach(Observer $observer) { $this->observers[] = $observer; } public function detach(Observer $observer) { $key = array_search($observer, $this->observers); if ($key !== false) { unset($this->observers[$key]); } } public function notify() { foreach ($this->observers as $observer) { $observer->update($this); } } } // 实战案例 $subject = new Subject(); $observer1 = new ConcreteObserver1(); $observer2 = new ConcreteObserver2(); $subject->attach($observer1); $subject->attach($observer2); $subject->notify(); // 输出:"ConcreteObserver1 received update from Subject" 和 "ConcreteObserver2 received update from Subject"
策略模式可讓您根據需要在不同演算法之間進行切換。
interface Strategy { public function doOperation($a, $b); } class ConcreteStrategyA implements Strategy { public function doOperation($a, $b) { return $a + $b; } } class ConcreteStrategyB implements Strategy { public function doOperation($a, $b) { return $a - $b; } } class Context { private $strategy; public function __construct(Strategy $strategy) { $this->strategy = $strategy; } public function doOperation($a, $b) { return $this->strategy->doOperation($a, $b); } } // 实战案例 $context = new Context(new ConcreteStrategyA()); echo $context->doOperation(10, 5); // 输出:15 $context = new Context(new ConcreteStrategyB()); echo $context->doOperation(10, 5); // 输出:5
指令模式將請求封裝成對象,讓您以參數化的方式執行它們。
interface Command { public function execute(); } class ConcreteCommand implements Command { private $receiver; public function __construct($receiver) { $this->receiver = $receiver; } public function execute() { $this->receiver->action(); } } class Receiver { public function action() { echo "Receiver action executed\n"; } } class Invoker { private $commands = []; public function setCommand(Command $command) { $this->commands[] = $command; } public function invoke() { foreach ($this->commands as $command) { $command->execute(); } } } // 实战案例 $receiver = new Receiver(); $command = new ConcreteCommand($receiver); $invoker = new Invoker(); $invoker->setCommand($command); $invoker->invoke(); // 输出:"Receiver action executed"
透過使用 PHP 中的行為型設計模式,您可以建立可重複使用、可維護且靈活的程式碼。
以上是PHP設計模式:與行為型程式設計的關係的詳細內容。更多資訊請關注PHP中文網其他相關文章!