设计模式 模板模式

转自:https://github.com/domnikl/DesignPatternsPHP

 1 abstract class Journey
 2 {
 3     private array $thingsToDo = [];
 4 
 5     final public function takeATrip()
 6     {
 7         $this->thingsToDo[] = $this->buyAFlight();
 8         $this->thingsToDo[] = $this->takePlane();
 9         $this->thingsToDo[] = $this->enjoyVacation();
10         $buyGift = $this->buyGift();
11 
12         if ($buyGift !== null) {
13             $this->thingsToDo[] = $buyGift;
14         }
15 
16         $this->thingsToDo[] = $this->takePlane();
17     }
18 
19     abstract protected function enjoyVacation(): string;
20 
21     protected function buyGift(): ?string
22     {
23         return null;
24     }
25 
26     private function buyAFlight(): string
27     {
28         return 'Buy a flight ticket';
29     }
30 
31     private function takePlane(): string
32     {
33         return 'Taking the plane';
34     }
35 
36     public function getThingsToDo(): array
37     {
38         return $this->thingsToDo;
39     }
40 }
 1 class CityJourney extends Journey
 2 {
 3     protected function enjoyVacation(): string
 4     {
 5         return "Eat, drink, take photos and sleep";
 6     }
 7 
 8     protected function buyGift(): ?string
 9     {
10         return "Buy a gift";
11     }
12 }
13 
14 class BeachJourney extends Journey
15 {
16     protected function enjoyVacation(): string
17     {
18         return "Swimming and sun-bathing";
19     }
20 }
 1 class JourneyTest extends TestCase
 2 {
 3     public function testCanGetOnVacationOnTheBeach()
 4     {
 5         $beachJourney = new BeachJourney();
 6         $beachJourney->takeATrip();
 7 
 8         $this->assertSame(
 9             ['Buy a flight ticket', 'Taking the plane', 'Swimming and sun-bathing', 'Taking the plane'],
10             $beachJourney->getThingsToDo()
11         );
12     }
13 
14     public function testCanGetOnAJourneyToACity()
15     {
16         $cityJourney = new CityJourney();
17         $cityJourney->takeATrip();
18 
19         $this->assertSame(
20             [
21                 'Buy a flight ticket',
22                 'Taking the plane',
23                 'Eat, drink, take photos and sleep',
24                 'Buy a gift',
25                 'Taking the plane'
26             ],
27             $cityJourney->getThingsToDo()
28         );
29     }
30 }

猜你喜欢

转载自www.cnblogs.com/ts65214/p/12968411.html
今日推荐