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

随心笔谈3年前发布 admin
212 0 0

文章摘要

这篇文章介绍了命令模式(Command Pattern)的实现,通过抽象命令类和具体命令类的结构展示了该模式的基本原理。文章中定义了`Command`抽象类,其核心属性为接收对象(Receiver),并通过继承的关系定义了两个具体命令类(ConcreteCommandA和ConcreteCommandB)。接收对象明确了多个命令的具体执行逻辑。文章详细说明了命令对象如何通过继承和方法重写扩展功能,并展示了客户端如何通过实例化命令对象并调用`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();

© 版权声明

相关文章