mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-07-31 20:20:15 +02:00
PHP7 TemplateMethod
This commit is contained in:
@@ -4,6 +4,11 @@ namespace DesignPatterns\Behavioral\TemplateMethod;
|
||||
|
||||
abstract class Journey
|
||||
{
|
||||
/**
|
||||
* @var string[]
|
||||
*/
|
||||
private $thingsToDo = [];
|
||||
|
||||
/**
|
||||
* This is the public service provided by this class and its subclasses.
|
||||
* Notice it is final to "freeze" the global behavior of algorithm.
|
||||
@@ -12,46 +17,49 @@ abstract class Journey
|
||||
*/
|
||||
final public function takeATrip()
|
||||
{
|
||||
$this->buyAFlight();
|
||||
$this->takePlane();
|
||||
$this->enjoyVacation();
|
||||
$this->buyGift();
|
||||
$this->takePlane();
|
||||
$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();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method must be implemented, this is the key-feature of this pattern.
|
||||
*/
|
||||
abstract protected function enjoyVacation();
|
||||
abstract protected function enjoyVacation(): string;
|
||||
|
||||
/**
|
||||
* This method is also part of the algorithm but it is optional.
|
||||
* This is an "adapter" (do not confuse with the Adapter pattern, not related)
|
||||
* You can override it only if you need to.
|
||||
* You can override it only if you need to
|
||||
*
|
||||
* @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';
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will be unknown by subclasses (better).
|
||||
* @return string[]
|
||||
*/
|
||||
private function buyAFlight()
|
||||
public function getThingsToDo(): array
|
||||
{
|
||||
echo "Buying a flight\n";
|
||||
return $this->thingsToDo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subclasses will get access to this method but cannot override it and
|
||||
* compromise this algorithm (warning : cause of cyclic dependencies).
|
||||
*/
|
||||
final protected function takePlane()
|
||||
{
|
||||
echo "Taking the plane\n";
|
||||
}
|
||||
|
||||
// A note regarding the keyword "final" : don't use it when you start coding :
|
||||
// add it after you narrow and know exactly what change and what remain unchanged
|
||||
// in this algorithm.
|
||||
// [abstract] x [3 access] x [final] = 12 combinations, it can be hard !
|
||||
}
|
||||
|
Reference in New Issue
Block a user