设计模式之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());
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);
$cc->runCommand('mail',null);
输出结果
Run UserCommand
Run MailCommand
李恺的博客已迁移到youyuge.com

浙公网安备 33010602011771号