命令链 模式以松散耦合主题为基础,发送消息、命令和请求,或通过一组处理程序发送任意内容。每个处理程序都会自行判断自己能否处理请求。如果可以,该请求被处理,进程停止。您可以为系统添加或移除处理程序,而不影响其他处理程序。
1 <?php 2 interface icommand{ 3 function oncommand($name,$arg); 4 }; 5 6 class commandchain{ 7 private $_commands=array(); 8 public function addCommand($cmd){ 9 $this->_commands[]=$cmd; 10 } 11 public function runCommand($name,$args) 12 { 13 foreach ($this->_commands as $cmd) 14 {$cmd->oncommand($name,$args);} 15 } 16 } 17 18 class mycommand implements icommand{ 19 function oncommand($name,$arg){ 20 if($name=='mytask'){ 21 echo 'it is my task'.'参数是'.$arg; 22 } 23 } 24 } 25 26 class yourcommand implements icommand{ 27 function oncommand($name,$arg){ 28 if($name=='yourtask'){ 29 echo 'it is your task'.'参数是'.$arg; 30 } 31 } 32 } 33 34 $mycom=new mycommand(); 35 $yourcom=new yourcommand(); 36 $comchain=new commandchain(); 37 $comchain->addCommand($mycom); 38 $comchain->addCommand($yourcom); 39 $comchain->runCommand('mytask',1); 40 $comchain->runCommand('yourtask',6); 41 42 43 44 ?>
代码依旧比较简单。请见谅。