正文

PHP设计模式中的命令模式(php常见的设计模式)不看后悔

文章摘要

这篇文章介绍了命令模式(Command Pattern)在PHP编程中的实现。文章通过示例展示了如何通过抽象命令类和具体命令类来统一定义命令接口。具体实现包括: 1. **抽象命令类**:定义了`Command`接口,包含了接收器对象和`execute()`方法。 2. **具体命令类**:实现了两个具体的命令类`ConcreteCommandA`和`ConcreteCommandB`,它们分别调用接收器的动作`actionA()`和`actionB()`。 3. **接收者类**:定义了`Receiver`类,实现了两个动作方法`actionA()`和`actionB()`,用于接收和执行命令。 4. **客户端代码**:展示了如何通过构造函数将接收器传递给命令类,并通过调用`execute()`方法来执行相应的操作。 文章重点突出了命令模式的灵活性和扩展性,通过继承和接口的共享,实现了不同命令的统一性和可重用性。

<?php // 抽象命令类 abstract class Command { protected $receiver; public function __construct(Receiver $receiver) { $this->receiver=$receiver; } abstract public function execute(); } // 具体命令类A class ConcreteCommandA extends Command { public function execute() { $this->receiver->actionA(); } } // 具体命令类B class ConcreteCommandB extends Command { public function execute() { $this->receiver->actionB(); } } // 接收者类 class Receiver { public function actionA() { echo “Receiver executes actionA.\n”; } public function actionB() { echo “Receiver executes actionB.\n”; } } // 客户端代码 $receiver=new Receiver(); $commandA=new ConcreteCommandA($receiver); $commandB=new ConcreteCommandB($receiver); $commandA->execute(); $commandB->execute();