执行逐步相关操作的最佳方法

时间:2014-05-26 09:39:24

标签: php design-patterns design-principles

实现这一目标的最佳方法是什么(可能使用某种设计模式)?

假设我们有3个阶段来处理用户输入,在每个阶段数据被验证/转换,如果成功,则执行下一步骤。如果上一步失败,则不需要继续下一步。

class PipeAndFilter
{
  protected $input;
  protected $proceedToNextStep;

  public function __construct(Array $input)
  {
     $this->input=$input;
     $this->proceedToNextStep=true;
  }

  public function process()
  {
    $this->filterOne();
    if(!$this->proceedToNextStep()) return false;
    $this->filterTwo();
    if(!$this->proceedToNextStep()) return false;
    $this>filterThree()
    return $this->proceedToNextStep();
  }

  protected function filterOne()
  {          
     //perform some action and set 
     //$this->proceedToNextStep
  }

  protected function filterTwo()
  {
    //perform some action and set 
     //$this->proceedToNextStep
  }

  protected function filterThree()
  {
     //do some filter and set 
     //$this->proceedToNextStep
  }

}

我认为上述课程足以描述问题。是否有更好的方法/设计模式来完成这项任务,可能使用单一类?

修改  有另一种方法,请你的意见! (未经测试)

class PipeAndFilter
{
  protected $callStack
  protected $input;
  /** fail states -ve numbers , success stats +ve numbers */
  protected $proceedToNextStep;

  public function __construct(Array $input)
  {
     $this->input=$input;
     $this->callStack=array();
     $this->callStack[]=array($this,'filterOne'));
     $this->callStack[]=array($this,'filterTwo'));
     $this->callStack[]=array($this,'filterThree'));
  }

  public function process()
  {
   foreach($this->callStack as $filterStep){
       call_user_func($filterStep);
       if(!$this->isProceedNext()) break;
   }
  }

  protected function isProceedNext()
  {       
    return $this->proceedToNextStep > 0 
  }

  protected function filterOne()
  {          
     //perform some action and set $this->proceedToNextStep

  }

  protected function filterTwo()
  {
     //perform some action and set $this->proceedToNextStep
  }

  protected function filterThree()
  {
     //perform some action and set $this->proceedToNextStep
  }

} 

1 个答案:

答案 0 :(得分:1)

我要看一下chain of responsibility模式。

链中的每个处理程序在输入(验证/转换)上执行它的操作并调用下一个处理程序,或者如果失败则停止执行。

相关问题