命令模式
约 413 字大约 1 分钟
2025-07-08
<?php
// 接收者:真正执行操作的对象
class Light {
public function turnOn() {
echo "Light is on<br>";
}
public function turnOff() {
echo "Light is off<br>";
}
}
// 命令接口:声明执行操作的方法
interface Command {
public function execute();
}
// 具体命令:将一个操作绑定到接收者
class TurnOnCommand implements Command {
private $light;
public function __construct(Light $light) {
$this->light = $light;
}
public function execute() {
$this->light->turnOn();
}
}
class TurnOffCommand implements Command {
private $light;
public function __construct(Light $light) {
$this->light = $light;
}
public function execute() {
$this->light->turnOff();
}
}
// 调用者:发起命令的对象
class RemoteControl {
private $command;
public function setCommand(Command $command) {
$this->command = $command;
}
public function pressButton() {
$this->command->execute();
}
}
// 客户端代码
$light = new Light();
$turnOnCommand = new TurnOnCommand($light);
$turnOffCommand = new TurnOffCommand($light);
$remoteControl = new RemoteControl();
$remoteControl->setCommand($turnOnCommand);
$remoteControl->pressButton(); // Light is on
$remoteControl->setCommand($turnOffCommand);
$remoteControl->pressButton(); // Light is off
在这个示例中,Light 类是接收者,负责执行实际的操作。Command 接口声明了执行操作的方法 execute()。TurnOnCommand 和 TurnOffCommand 是具体命令类,将操作绑定到 Light 接收者上。RemoteControl 类是调用者,负责发起命令。客户端代码创建了 Light 对象和相应的命令对象,并将命令对象设置到遥控器上,然后按下按钮执行命令。
命令模式的主要优点在于:
- 将命令发送者和接收者解耦,使得发送者不需要知道接收者的具体实现。
- 可以轻松地添加新的命令,而无需更改调用者的代码。
在这个示例中,如果需要添加新的操作,只需创建一个新的具体命令类并实现 Command 接口即可,而不需要修改调用者 RemoteControl 的代码。