模板方法模式是一種讓抽象模板的子類「完成」一系列算法的行爲策略。php
衆所周知的「好萊塢原則」:「不要打電話給咱們,咱們會打電話給你」。這個類不是由子類調用的,而是以相反的方式。怎麼作?固然很抽象啦!laravel
換而言之,它是一種很是適合框架庫的算法骨架。用戶只須要實現子類的一種方法,其父類即可去搞定這項工做了。面試
這是一種分離具體類的簡單辦法,且能夠減小複製粘貼,這也是它常見的緣由。算法
<?php namespace DesignPatterns\Behavioral\TemplateMethod; abstract class Journey { /** * @var string[] */ private $thingsToDo = []; /** * 這是當前類及其子類提供的公共服務 * 注意,它「凍結」了全局的算法行爲 * 若是你想重寫這個契約,只須要實現一個包含 takeATrip() 方法的接口 */ final public function takeATrip() { $this->thingsToDo[] = $this->buyAFlight(); $this->thingsToDo[] = $this->takePlane(); $this->thingsToDo[] = $this->enjoyVacation(); $buyGift = $this->buyGift(); if ($buyGift !== null) { $this->thingsToDo[] = $buyGift; } $this->thingsToDo[] = $this->takePlane(); } /** * 這個方法必需要實現,它是這個模式的關鍵點 */ abstract protected function enjoyVacation(): string; /** * 這個方法是可選的,也可能做爲算法的一部分 * 若是須要的話你能夠重寫它 * * @return null|string */ protected function buyGift() { return null; } private function buyAFlight(): string { return 'Buy a flight ticket'; } private function takePlane(): string { return 'Taking the plane'; } /** * @return string[] */ public function getThingsToDo(): array { return $this->thingsToDo; } }
<?php namespace DesignPatterns\Behavioral\TemplateMethod; class BeachJourney extends Journey { protected function enjoyVacation(): string { return "Swimming and sun-bathing"; } }
<?php namespace DesignPatterns\Behavioral\TemplateMethod; class CityJourney extends Journey { protected function enjoyVacation(): string { return "Eat, drink, take photos and sleep"; } protected function buyGift(): string { return "Buy a gift"; } }
<?php namespace DesignPatterns\Behavioral\TemplateMethod\Tests; use DesignPatterns\Behavioral\TemplateMethod; use PHPUnit\Framework\TestCase; class JourneyTest extends TestCase { public function testCanGetOnVacationOnTheBeach() { $beachJourney = new TemplateMethod\BeachJourney(); $beachJourney->takeATrip(); $this->assertEquals( ['Buy a flight ticket', 'Taking the plane', 'Swimming and sun-bathing', 'Taking the plane'], $beachJourney->getThingsToDo() ); } public function testCanGetOnAJourneyToACity() { $cityJourney = new TemplateMethod\CityJourney(); $cityJourney->takeATrip(); $this->assertEquals( [ 'Buy a flight ticket', 'Taking the plane', 'Eat, drink, take photos and sleep', 'Buy a gift', 'Taking the plane' ], $cityJourney->getThingsToDo() ); } }
PHP 互聯網架構師成長之路*「設計模式」終極指南shell
PHP 互聯網架構師 50K 成長指南+行業問題解決總綱(持續更新)設計模式
面試10家公司,收穫9個offer,2020年PHP 面試問題服務器
★若是喜歡個人文章,想與更多資深開發者一塊兒交流學習的話,獲取更多大廠面試相關技術諮詢和指導,歡迎加入咱們的羣啊,暗號:phpzh(君羊號碼856460874)。架構
內容不錯的話但願你們支持鼓勵下點個贊/喜歡,歡迎一塊兒來交流;另外若是有什麼問題 建議 想看的內容能夠在評論提出