サーチ…


責任連鎖の例(Php)

あるオブジェクトで呼び出されたメソッドは、呼び出しを適切に処理できるオブジェクトが見つかるまで、オブジェクトのチェーンを上に移動します。この特定の例では、実験のタイトル、実験ID、または実験で使用された組織を取得できる機能を備えた科学実験を使用しています。

abstract class AbstractExperiment {
    abstract function getExperiment();
    abstract function getTitle();
}
 
class Experiment extends AbstractExperiment {
    private $experiment;
    private $tissue;
    function __construct($experiment_in) {
        $this->experiment = $experiment_in;
        $this->tissue = NULL;
    }
    function getExperiment() {
        return $this->experiment;
    }
    //this is the end of the chain - returns title or says there is none
    function getTissue() {
      if (NULL != $this->tissue) {
        return $this->tissue;
      } else {
        return 'there is no tissue applied';
      }
    }
}

class SubExperiment extends AbstractExperiment {
    private $experiment;
    private $parentExperiment;
    private $tissue;
    function __construct($experiment_in, Experiment $parentExperiment_in) {
      $this->experiment = $experiment_in;
      $this->parentExperiment = $parentExperiment_in;
      $this->tissue = NULL;
    }
    function getExperiment() {
      return $this->experiment;
    }
    function getParentExperiment() {
      return $this->parentExperiment;
    }   
    function getTissue() {
      if (NULL != $this->tissue) {
        return $this->tissue;
      } else {
        return $this->parentExperiment->getTissue();
      }
    }
}

//This class and all further sub classes work in the same way as SubExperiment above
class SubSubExperiment extends AbstractExperiment {
    private $experiment;
    private $parentExperiment;
    private $tissue;
    function __construct($experiment_in, Experiment $parentExperiment_in) { //as above }
    function getExperiment() { //same as above }
    function getParentExperiment() { //same as above }   
    function getTissue() { //same as above }
}


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow