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

 2025-01-16  阅读 409  评论 8  点赞 245

摘要:复制代码 代码如下:
复制代码 代码如下:

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


标签:phpphp教程

评论列表:

显示更多评论

发表评论:

管理员

承接各种程序开发,外贸网站代运营,外贸网站建设等项目
  • 内容2460
  • 积分67666
  • 金币86666

Copyright © 2024 LS'Blog-保定PHP程序员老宋个人博客 Inc. 保留所有权利。 Powered by LS'blog 3.0.3

页面耗时0.0281秒, 内存占用1.93 MB, 访问数据库29次

冀ICP备19034377号