PHP设计模式学习笔记: 策略模式

// 策略生成器(有点相当于工厂)
class StrategyContext {
    private $strategy = NULL; 
    //bookList is not instantiated at construct time
    public function __construct($strategy_ind_id) {
        switch ($strategy_ind_id) {
            case "Makeupper": 
                $this->strategy = new StrategyMakeupper();
            break;
            case "Makeimportant": 
                $this->strategy = new StrategyMakeimportant();
            break;
            case "Makefavorate": 
                $this->strategy = new StrategyMakefavorate();
            break;
        }
    }
    public function showBookTitle($book) {
      return $this->strategy->showTitle($book);
    }
}

// 定义一个策略接口,让所有实现该接口的策略类都保持有showTitle()这个规范的方法
interface StrategyInterface {
    public function showTitle($book_in);
}

class StrategyMakeupper implements StrategyInterface {
    public function showTitle($book_in) {
        $title = $book_in->getTitle();
        return strtoupper($title);
    }
}

class StrategyMakeimportant implements StrategyInterface {
    public function showTitle($book_in) {
        $title = $book_in->getTitle();
        return str_replace(' ','!',$title);
    }
}

class StrategyMakefavorate implements StrategyInterface {
    public function showTitle($book_in) {
        $title = $book_in->getTitle();
        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('开始测试策略模式');
  writeln('');

  $book = new Book('这是书名标题《abc》  ^o^');
 
  // 给策略生成器工厂传递一个策略参数,就得到了不同的策略对象
  $strategyContextMakeupper = new StrategyContext('Makeupper');
  $strategyContextMakeimportant = new StrategyContext('Makeimportant');
  $strategyContextMakefavorate = new StrategyContext('Makefavorate');
 
  writeln('测试 1 - 显示大写后的书名');
  // 调用策略对象的方法都是一样的( showBookTitle() ),给其传递的参数也是一样的($book)
  // 但因为策略对象不一样,所以结果不一样。对象不同,结果不同,结果不同的根本原因在于传递了不同的“策略参数”
  writeln($strategyContextMakeupper->showBookTitle($book));
  writeln('');

  writeln('测试 2 - 显示标识为重要的书名');
  writeln($strategyContextMakeimportant->showBookTitle($book));
  writeln('');
 
  writeln('测试 3 - 显示标识为收藏的书名');
  writeln($strategyContextMakefavorate->showBookTitle($book));
  writeln('');

  writeln('结束测试策略模式');

  function writeln($line_in) {
    echo $line_in.PHP_EOL;
  }

结果:

开始测试策略模式

测试 1 - 显示大写后的书名
这是书名标题《ABC》  ^O^

测试 2 - 显示标识为重要的书名
这是书名标题《abc》!!^o^

测试 3 - 显示标识为收藏的书名
这是书名标题《abc》**^o^

结束测试策略模式



EOF





你可能感兴趣的:(PHP设计模式学习笔记: 策略模式)