设计模式之Command

 

代码
<?php
interface ICommand
{
function onCommand($name,$args);
}

class CommandChain
{
private$_commands=array();

publicfunction addCommand($cmd)
{
$this->_commands[] =$cmd;
}

publicfunction runCommand($name,$args)
{
foreach ($this->_commands as$cmd) {
if ($cmd->onCommand($name,$args)) {
return;
}
}
}
}

class UserCommand implements ICommand
{
publicfunction onCommand($name,$args)
{
if ($name!='addUser') {
returnfalse;
}

echo"Run UserCommand <br />";
returntrue;
}
}

class MailCommand implements ICommand
{
publicfunction onCommand($name,$args)
{
if ($name!='mail') {
returnfalse;
}

echo"Run MailCommand <br />";
}
}

$cc=new CommandChain();
$cc->addCommand(new UserCommand());
$cc->addCommand(new MailCommand());
$cc->runCommand('addUser',null);
$cc->runCommand('mail',null);

 

 输出结果

Run UserCommand
Run MailCommand

 

 

李恺的博客已迁移到youyuge.com

posted on 2010-01-25 20:04  李恺  阅读(65)  评论(0)    收藏  举报