The Template Method pattern is a behavioral design pattern that defines the skeleton of an algorithm in a method, deferring some steps to subclasses. This pattern lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure
In this article, we’ll explore the Template Method pattern using a simple sandwich-making example in PHP. We’ll create two types of sandwiches: VeggySub
and TurkeySub
.
The Concept
Imagine we have a base class Sub
that outlines the steps to make a sandwich. Some steps are common to all sandwiches (like laying bread and adding chaos), while the main ingredient varies (like veggies or turkey). The Template Method pattern allows us to define these steps in the base class and leave the specifics of the main ingredient to the subclasses.
The Implementation
Step 1: Creating the Base Class
First, we create an abstract class Sub
that defines the template method make
. This method outlines the steps to make a sandwich. The addPrimaryToppings
method is abstract and will be implemented by subclasses.
namespace App;
abstract class Sub
{
protected abstract function addPrimaryToppings();
protected function layBread()
{
var_dump("Laying Bread");
return $this;
}
protected function addChaos()
{
var_dump("Adding Chaos");
return $this;
}
public function make()
{
return $this->layBread()
->addChaos()
->addPrimaryToppings();
}
}
Step 2: Creating Subclasses
Next, we create two subclasses: VeggySub
and TurkeySub
. Each subclass implements the addPrimaryToppings
method to add its specific ingredients.
- VeggySub
namespace App;
class VeggySub extends Sub
{
protected function addPrimaryToppings()
{
var_dump("Adding Veggy");
return $this;
}
}
2. TurkeySub
namespace App;
class TurkeySub extends Sub
{
protected function addPrimaryToppings()
{
var_dump("Adding Turkey");
return $this;
}
}
Step 3: Using the Template Method
Finally, we create an entry point to test our sandwich-making process.
(new \App\VeggySub())->make();
echo "------------\n";
(new \App\TurkeySub())->make();
When we run this script, it will output the steps to make a Veggy sandwich followed by a Turkey sandwich:
Laying Bread
Adding Chaos
Adding Veggy
------------
Laying Bread
Adding Chaos
Adding Turkey
The Template Method pattern is a powerful way to define the structure of an algorithm while allowing subclasses to provide specific implementations for certain steps. In our example, the Sub
class defines the general process for making a sandwich, while VeggySub
and TurkeySub
provide the details for their respective ingredients.
By using the Template Method pattern, you can ensure that the overall algorithm remains consistent across different implementations, while allowing flexibility in specific steps. This approach promotes code reuse and helps maintain a clear structure in your applications.
You can find the complete source code for this example on GitHub.