模板方法是一种行为设计模式。
你可能已经遇到过很多次了。它的思想是让这个抽象模板的子类【完成】算法的行为策略。
也就是【好莱坞原则】:【别打给我们,我们打给你】。这个类不是由子类调用的,而是由相反的子类调用的。怎么样?当然是抽象的。
换句话说,这是一个算法框架,非常适合框架库。用户只需要实现一个方法,超类就可以完成这项工作。
它是解耦具体类和减少复制黏贴的一种简单方法,这就是为什么你会发现它无处不在。
Journey.php
<?php declare(strict_types=1); namespace DesignPatternsBehavioralTemplateMethod; abstract class Journey { private array $thingsToDo = []; 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; protected function buyGift(): ?string { return null; } private function buyAFlight(): string { return "Buy a flight ticket"; } private function takePlane(): string { return "Taking the plane"; } public function getThingsToDo(): array { return $this->thingsToDo; } }
BeachJourney.php
<?php declare(strict_types=1); namespace DesignPatternsBehavioralTemplateMethod; class BeachJourney extends Journey { protected function enjoyVacation(): string { return "Swimming and sun-bathing"; } }
CityJourney.php
<?php declare(strict_types=1); namespace DesignPatternsBehavioralTemplateMethod; class CityJourney extends Journey { protected function enjoyVacation(): string { return "Eat, drink, take photos and sleep"; } protected function buyGift(): ?string { return "Buy a gift"; } }
Tests/JourneyTest.php
<?php declare(strict_types=1); namespace DesignPatternsBehavioralTemplateMethodTests; use DesignPatternsBehavioralTemplateMethodBeachJourney; use DesignPatternsBehavioralTemplateMethodCityJourney; use PHPUnitFrameworkTestCase; class JourneyTest extends TestCase { public function testCanGetOnVacationOnTheBeach() { $beachJourney = new BeachJourney(); $beachJourney->takeATrip(); $this->assertSame( ["Buy a flight ticket", "Taking the plane", "Swimming and sun-bathing", "Taking the plane"], $beachJourney->getThingsToDo() ); } public function testCanGetOnAJourneyToACity() { $cityJourney = new CityJourney(); $cityJourney->takeATrip(); $this->assertSame( [ "Buy a flight ticket", "Taking the plane", "Eat, drink, take photos and sleep", "Buy a gift", "Taking the plane" ], $cityJourney->getThingsToDo() ); } }
目的相比 简单工厂模式(SimpleFactory)而言,工厂方法模式(Factory Method)可以通过延伸出子类,实现用不同的方法创建对象。...
黑盒测试,白盒测试与灰盒测试的比较和区别如下所示:编号黑盒测试白盒测试灰盒测试1不需要了解内部工作结构(代码)。测试用例只...
定位符是小型数据结构,包含用于访问LOB实际数据的信息。在数据库的表中,定位符直接存储在表中,而数据可以存储在表中或单...
可以使用 Fetch Size 更改行获取值来更改每次访问数据库游标时检索的行数。默认情况下,OceanBase Connector/J 运行查询时,默认...
OceanBase Connector/J 支持登录认证和 SSL 安全功能。登录认证客户端身份验证服务支持添加新的客户端身份验证插件。Java 连接器...