PHP設計模式學習筆記: 模版方法

jopen 10年前發布 | 15K 次閱讀 PHP設計模式 PHP開發

翻譯: 

http://sourcemaking.com/design_patterns/template_method

http://sourcemaking.com/design_patterns/template_method/php

abstract class TemplateAbstract {
    public final function showBookTitleInfo($book_in) {
        $title = $book_in->getTitle();
        $author = $book_in->getAuthor();
        $processedTitle = $this->processTitle($title);
        $processedAuthor = $this->processAuthor($author);
        if (NULL == $processedAuthor) {
            $processed_info = $processedTitle;
        } else {
            $processed_info = $processedTitle.' by '.$processedAuthor;
        }
        return $processed_info;
    }

    abstract function processTitle($title);  
    function processAuthor($author) {
        return NULL;
    } 
}

class TemplateExclaim extends TemplateAbstract {
    function processTitle($title) {
      return str_replace(' ','!!!',$title); 
    }

    function processAuthor($author) {
      return str_replace(' ','!!!',$author);
    }
}

class TemplateStars extends TemplateAbstract {
    function processTitle($title) {
        return str_replace(' ','*',$title); 
    }
}

class Book {
    private $author;
    private $title;

    function __construct($title_in, $author_in) {
        $this->author = $author_in;
        $this->title  = $title_in;
    }
    function getAuthor() {return $this->author;}
    function getTitle() {return $this->title;}
    function getAuthorAndTitle() {
        return $this->getTitle() . ' by ' . $this->getAuthor();
    }
}

  writeln('開始測試模版方法');echo PHP_EOL;

  $book = new Book('PHP for Cats','Larry Truett');

  $exclaimTemplate = new TemplateExclaim();  
  $starsTemplate = new TemplateStars();

  writeln('test 1 - show exclaim template');echo PHP_EOL;
  writeln($exclaimTemplate->showBookTitleInfo($book));echo PHP_EOL;

  writeln('test 2 - show stars template');echo PHP_EOL;
  writeln($starsTemplate->showBookTitleInfo($book));echo PHP_EOL;


  writeln('END TESTING TEMPLATE PATTERN');

  function writeln($line_in) {
    echo $line_in;
  }
原文地址:http://sourcemaking.com/design_patterns/template_method/php

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!