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

随心笔谈12个月前发布 admin
93 0

<?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();

© 版权声明

相关文章