时间:2021-05-26
复制代码 代码如下:
<?php
/**
* 命令模式
*
* 将一个请求封装为一个对象从而使你可用不同的请求对客户进行参数化,对请求排除或记录请求日志,以及支持可取消的操作
*/
interface Command
{
public function execute();
}
class Invoker
{
private $_command = array();
public function setCommand($command) {
$this->_command[] = $command;
}
public function executeCommand()
{
foreach($this->_command as $command)
{
$command->execute();
}
}
public function removeCommand($command)
{
$key = array_search($command, $this->_command);
if($key !== false)
{
unset($this->_command[$key]);
}
}
}
class Receiver
{
private $_name = null;
public function __construct($name) {
$this->_name = $name;
}
public function action()
{
echo $this->_name." action<br/>";
}
public function action1()
{
echo $this->_name." action1<br/>";
}
}
class ConcreteCommand implements Command
{
private $_receiver;
public function __construct($receiver)
{
$this->_receiver = $receiver;
}
public function execute()
{
$this->_receiver->action();
}
}
class ConcreteCommand1 implements Command
{
private $_receiver;
public function __construct($receiver)
{
$this->_receiver = $receiver;
}
public function execute()
{
$this->_receiver->action1();
}
}
class ConcreteCommand2 implements Command
{
private $_receiver;
public function __construct($receiver)
{
$this->_receiver = $receiver;
}
public function execute()
{
$this->_receiver->action();
$this->_receiver->action1();
}
}
$objRecevier = new Receiver("No.1");
$objRecevier1 = new Receiver("No.2");
$objRecevier2 = new Receiver("No.3");
$objCommand = new ConcreteCommand($objRecevier);
$objCommand1 = new ConcreteCommand1($objRecevier);
$objCommand2 = new ConcreteCommand($objRecevier1);
$objCommand3 = new ConcreteCommand1($objRecevier1);
$objCommand4 = new ConcreteCommand2($objRecevier2); // 使用 Recevier的两个方法
$objInvoker = new Invoker();
$objInvoker->setCommand($objCommand);
$objInvoker->setCommand($objCommand1);
$objInvoker->executeCommand();
$objInvoker->removeCommand($objCommand1);
$objInvoker->executeCommand();
$objInvoker->setCommand($objCommand2);
$objInvoker->setCommand($objCommand3);
$objInvoker->setCommand($objCommand4);
$objInvoker->executeCommand();
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了PHP命令Command模式用法。分享给大家供大家参考,具体如下:命令Command模式是GOF23种模式中的一种,是一种行为模式。这种模式很难理
命令模式(Command),命令模式是封装一个通用操作的机制。如果你熟悉C或PHP,你可能已经遇到过Command,它相当于程序中的:回调(callback)。
vi的两种命令模式;Command(命令)模式,用于输入命令;Insert(插入)模式,用于插入文本;Visual(可视)模式,用于视化的的高亮并选定正文;Co
php设计模式有以下几种模式: 1、命令链模式,命令链模式以松散耦合主题为基础,发送消息、命令和请求,或通过一组处理程序发送任意内容。每个处理程序都会自行判断