1、模式定义
模板方法模式又叫模板模式,该模式在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。
模板方法模式将主要的方法定义为 final ,防止子类修改算法骨架,将子类必须实现的方法定义为 abstract 。而普通的方法(无 final 或 abstract 修饰)则称之为钩子( hook )。
2、UML类图
3、示例代码
Journey.php
<?phpnamespace DesignPatterns\Behavioral\TemplateMethod;abstract class Journey{ /** * 该方法是父类和子类提供的公共服务 * 注意到方法前加了final,意味着子类不能重写该方法 */ final public function takeATrip() { $this->buyAFlight(); $this->takePlane(); $this->enjoyVacation(); $this->buyGift(); $this->takePlane(); } /** * 该方法必须被子类实现, 这是模板方法模式的核心特性 */ abstract protected function enjoyVacation(); /** * 这个方法也是算法的一部分,但是是可选的,只有在需要的时候才去重写它 */ protected function buyGift() { } /** * 子类不能访问该方法 */ private function buyAFlight() { echo "Buying a flight\n"; } /** * 这也是个final方法 */ final protected function takePlane() { echo "Taking the plane\n"; }}
BeachJourney.php
<?phpnamespace DesignPatterns\Behavioral\TemplateMethod;/** * BeachJourney类(在海滩度假) */class BeachJourney extends Journey{ protected function enjoyVacation() { echo "Swimming and sun-bathing\n"; }}
CityJourney.php
<?phpnamespace DesignPatterns\Behavioral\TemplateMethod;/** * CityJourney类(在城市中度假) */class CityJourney extends Journey{ protected function enjoyVacation() { echo "Eat, drink, take photos and sleep\n"; }}
4、测试代码
Tests/JourneyTest.php
<?phpnamespace DesignPatterns\Behavioral\TemplateMethod\Tests;use DesignPatterns\Behavioral\TemplateMethod;/** * JourneyTest测试所有的度假 */class JourneyTest extends \PHPUnit_Framework_TestCase{ public function testBeach() { $journey = new TemplateMethod\BeachJourney(); $this->expectOutputRegex('#sun-bathing#'); $journey->takeATrip(); } public function testCity() { $journey = new TemplateMethod\CityJourney(); $this->expectOutputRegex('#drink#'); $journey->takeATrip(); } /** * 在PHPUnit中如何测试抽象模板方法 */ public function testLasVegas() { $journey = $this->getMockForAbstractClass('DesignPatterns\Behavioral\TemplateMethod\Journey'); $journey->expects($this->once()) ->method('enjoyVacation') ->will($this->returnCallback(array($this, 'mockUpVacation'))); $this->expectOutputRegex('#Las Vegas#'); $journey->takeATrip(); } public function mockUpVacation() { echo "Fear and loathing in Las Vegas\n"; }}
5、总结
模板方法模式是基于继承的代码复用技术,模板方法模式的结构和用法也是面向对象设计的核心之一。在模板方法模式中,可以将相同的代码放在父类中,而将不同的方法实现放在不同的子类中。
在模板方法模式中,我们需要准备一个抽象类,将部分逻辑以具体方法以及具体构造函数的形式实现,然后声明一些抽象方法来让子类实现剩余的逻辑。不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现,这就是模板方法模式的用意。模板方法模式体现了面向对象的诸多重要思想,是一种使用频率较高的模式。

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

依賴性(di)inphpenhancesCodeFlexibility andTestability by decouplingClassesscyclasses fromtheippentencies.1)UseConstructorientoctionTopAssDopassDectiesViactructors Viactructors

推薦Pimple用於簡單項目,Symfony的DependencyInjection用於復雜項目。 1)Pimple適合小型項目,因其簡單和靈活。 2)Symfony的DependencyInjection適合大型項目,因其功能強大。選擇時需考慮項目規模、性能需求和學習曲線。

依賴性注射(DI)InphpisadesignpatternwhereClassDepentenciesArepassedtotosedTosedTosedTotratherThancReateDinterally,增強codemodemodularityAndTestabily.itimprovessoftwarequalitybyby By:1)增強tosestabilityTestabilityTestabilityThroughityThroughEasyDepentyDepententymydependentymocking,2)增強Flexibilybya


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

記事本++7.3.1
好用且免費的程式碼編輯器

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境