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

yipeiwu_com5年前PHP代码库
复制代码 代码如下:

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

相关文章

php强制下载文件函数

本文实例为大家分享了php强制下载文件函数,供大家参考,具体内容如下 public function down() { $id = $this->_get('id');...

PHP用continue跳过本次循环中剩余代码的注意点

前言 大家都知道,在PHP中continue 在循环结构用用来跳过本次循环中剩余的代码并在条件求值为真时开始执行下一次循环。一定要注意的是,用了continue要用“;”来隔开其他的代码...

PHP解决中文乱码

在php中,中文乱码非常头疼,很麻烦,所以根据在编程的经验,总结以下方法(以utf_8为例), 1.php中在头部header设置编码方式 header("Content-type:te...

Drupal7 form表单二次开发要点与实例

请记得收藏此文,在你进行Drupal 7 custom module时,经常会用到的form 表单的跳转或重载。主要汇总三个要点: 1.页面提交后,经过#submit处理后,需要redi...

PHP读取txt文件的内容并赋值给数组的代码

2010-12-15.txt的文件内容如下: 复制代码 代码如下: 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20...