php设计模式 – 命令链模式
前面我们介绍了设计模式在php编程中的一些应用: 使用接口实现松散耦合, 观察者模式。
这篇文章我们来介绍一下另外一个设计模式命令链模式, 与观察者模式一样,使用命令链模式可以是php各组件之间避免紧密耦合。

命令链 模式以松散耦合主题为基础,发送消息、命令和请求,或通过一组处理程序发送任意内容。每个处理程序都会自行判断自己能否处理请求。如果可以,该请求被处理,进程停止。您可以为系统添加或移除处理程序,而不影响其他处理程序。下面的代码显示了此模式的一个示例。
[php]
<?php
interface ICommand
{
function onCommand( $name, $args );
}
class CommandChain
{
private $_commands = array();
public function addCommand( $cmd )
{
$this->_commands []= $cmd;
}
public function runCommand( $name, $args )
{
foreach( $this->_commands as $cmd )
{
if ( $cmd->onCommand( $name, $args ) )
return;
}
}
}
class UserCommand implements ICommand
{
public function onCommand( $name, $args )
{
if ( $name != ‘addUser’ ) return false;
echo( "UserCommand handling ‘addUser’\n" );
return true;
}
}
class MailCommand implements ICommand
{
public function onCommand( $name, $args )
{
if ( $name != ‘mail’ ) return false;
echo( "MailCommand handling ‘mail’\n" );
return true;
}
}
$cc = new CommandChain();
$cc->addCommand( new UserCommand() );
$cc->addCommand( new MailCommand() );
$cc->runCommand( ‘addUser’, null );
$cc->runCommand( ‘mail’, null );
?>
[/php]
此代码定义维护 ICommand 对象列表的 CommandChain 类。两个类都可以实现 ICommand 接口 —— 一个对邮件的请求作出响应,另一个对添加用户作出响应。
如果您运行包含某些测试代码的脚本,则会得到以下输出:
[php]
% php chain.php
UserCommand handling ‘addUser’
MailCommand handling ‘mail’
%
[/php]
代码首先创建 CommandChain 对象,并为它添加两个命令对象的实例。然后运行两个命令以查看谁对这些命令作出了响应。如果命令的名称匹配 UserCommand 或 MailCommand,则代码失败,不发生任何操作。
为处理请求而创建可扩展的架构时,命令链模式很有价值,使用它可以解决许多问题。
作者: 石巍
原载: 五种常见的 PHP 设计模式
版权所有,转载时必须以超链接形式注明作者和原始出处及本声明。