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;
  }



todo

你可能感兴趣的:(PHP设计模式学习笔记: 模版方法)