PHP設計模式學習筆記: 策略模式

jopen 10年前發布 | 21K 次閱讀 PHP設計模式 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; }</pre>

結果:

開始測試策略模式

測試 1 - 顯示大寫后的書名
這是書名標題《ABC》  ^O^

測試 2 - 顯示標識為重要的書名
這是書名標題《abc》!!^o^

測試 3 - 顯示標識為收藏的書名
這是書名標題《abc》**^o^

結束測試策略模式

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