forget for get

覚えるために忘れる

Template Methodパターン

スーパークラスで抽象メソッドの呼び出しの流れを定め、サブクラスで具体的な処理を実装
ロジックが共通化できる

 

AbstractDisplay.php

abstract class AbstractDisplay {
  abstract function open();
  abstract function print();
  abstract function close();
  function display() {
    $this->open();
    $this->print();
    $this->close();
  }
}

CharDisplay.php

class CharDisplay extends AbstractDisplay {
  private $ch;
  function __construct($ch) {
    $this->ch = $ch;
  }
  function open() {
    echo "<<";
  }
  function print() {
    echo $this->ch;
  }
  function close() {
    echo ">>\n";
  }
}

StringDisplay.php

class StringDisplay extends AbstractDisplay {
  private $string;
  private $width;
  function __construct($string) {
    $this->string = $string;
    $this->width = strlen($string);
  }
  function open() {
    $this->printLine();
  }
  function print() {
    echo "|" . $this->string . "|\n";
  }
  function close() {
    $this->printLine();
  }
  private function printLine() {
    echo "+";
    for ($i=0;$i<$this->width;$i++) {
      echo "-";
    }
    echo "+\n";
  }
}

Main.php

require "../autoload.php";
$d1 = new CharDisplay("H");
$d2 = new StringDisplay("Hello");
$d1->display();
$d2->display();