PHP中的设计模式:带代码示例的高级技术
设计模式是软件开发中常见问题的经过验证的解决方案。如果您已经掌握了基础模式(Singleton、Factory、Observer),那么是时候进入下一个层次了。在本文中,我们将分析PHP中的四种高级行为模式:策略、命令、状态和职责链。您将了解它们如何帮助编写灵活、可维护和可扩展的代码。
1. 策略模式 (Strategy)
策略模式允许定义一系列算法,将每个算法封装起来,并使它们可以相互替换。当您有几种执行同一任务的方式,并且希望在不修改主类的情况下轻松切换它们时,这尤其有用。
何时使用:
- 您有多个算法变体,可能在运行时发生变化。
- 您希望避免冗长的条件结构(if-else或switch)。
- 算法可以在应用程序的不同部分重复使用。
示例:运费计算系统
假设您有一个在线商店,运费取决于所选承运商:俄罗斯邮政、DHL或快递服务。
<?php
// 策略接口interface ShippingStrategy { public function calculate(float $weight, float $distance): float;}
// 具体策略class RussianPostShipping implements ShippingStrategy { public function calculate(float $weight, float $distance): float { return ($weight * 0.5) + ($distance * 0.1); }}
class DHLShipping implements ShippingStrategy { public function calculate(float $weight, float $distance): float { return ($weight * 1.2) + ($distance * 0.3) + 10; }}
class CourierShipping implements ShippingStrategy { public function calculate(float $weight, float $distance): float { return ($weight * 0.8) + ($distance * 0.2) + 5; }}
// 上下文class Order { private float $weight; private float $distance; private ShippingStrategy $strategy;
public function __construct(float $weight, float $distance, ShippingStrategy $strategy) { $this->weight = $weight; $this->distance = $distance; $this->strategy = $strategy; }
public function setStrategy(ShippingStrategy $strategy): void { $this->strategy = $strategy; }
public function getShippingCost(): float { return $this->strategy->calculate($this->weight, $this->distance); }}
// 使用$order = new Order(2.5, 100, new RussianPostShipping());echo "俄罗斯邮政运费:" . $order->getShippingCost() . " 卢布";
$order->setStrategy(new DHLShipping());echo "DHL运费:" . $order->getShippingCost() . " 卢布";?>在此示例中,我们轻松更改了运费计算算法,而无需修改Order类。添加新承运商只需创建一个实现ShippingStrategy接口的新类。
2. 命令模式 (Command)
命令模式将请求转换为对象,允许使用不同的请求对客户端进行参数化、将请求排入队列、记录它们或支持操作撤销。
何时使用:
- 需要实现操作的撤销(undo)和重做(redo)。
- 需要将操作排入队列或异步执行。
- 您希望将请求的发送者与其接收者分离。
示例:带撤销功能的文本编辑器
<?php
// 命令接口interface Command { public function execute(): void; public function undo(): void;}
// 接收者 (Receiver)class