设计模式之Command

 

代码
<?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 "Run UserCommand <br />";
return true;
}
}

class MailCommand implements ICommand
{
public function onCommand($name, $args)
{
if ($name != 'mail') {
return false;
}

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

 

 

posted on 2010-01-31 13:48  李恺  阅读(105)  评论(0)    收藏  举报