Template Method design pattern

The Template Method design pattern is used to create a group of subclasses that have to execute a similar group of behaviors.

This design pattern consists of a Template Method, which is an abstract class. Concrete subclasses can override the methods within the abstract class. The Template Method consists of a skeleton of an algorithm; the subclasses can use overriding to change the concrete behavior of the algorithm.

As such, this is an incredibly simple design pattern to use; it encourages loose coupling while also controlling at what points subclassing is permitted. Thus, it is more fine-grained than simple polymorphic behavior.

Consider the following abstraction of a Pasta class:

<?php abstract class Pasta { public ...

Get Mastering PHP Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.