社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
命令模式(Command):将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
/** * 命令抽象类 * Interface Command */ interface Command { /** * @return mixed */ public function execute(); } /** * 具体命令类 * Class ConcreteCommand */ class ConcreteCommand implements Command { /** * @var Receiver */ protected $receiver; /** * ConcreteCommand constructor. * @param Receiver $receiver */ public function __construct(Receiver $receiver) { $this->receiver = $receiver; } /** * @return mixed|void */ public function execute() { // TODO: Implement execute() method. $this->receiver->action(); } } /** * 命令发送者 * Class Invoker */ class Invoker { /** * @var */ protected $command; /** * @param Command $command */ public function setCommand(Command $command) { $this->command = $command; } /** * 执行 */ public function run() { $this->command->execute(); } } /** * 命令接收者 * Class Receiver */ class Receiver { /** * 执行请求 */ public function action() { echo "执行请求"; } } # 客户端代码 // 设定接收者 $receiver = new Receiver(); $command = new ConcreteCommand($receiver); // 发送命令 $invoker = new Invoker(); $invoker->setCommand($command); $invoker->run();
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!