欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php设计模式 Command(命令模式)

程序员文章站 2023-02-26 15:33:01
复制代码 代码如下:
复制代码 代码如下:

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