Search⌘ K
AI Features

Template Pattern

Explore the Template pattern in Node.js to learn how abstract classes define core component structures while subclasses fill in specific steps. This lesson helps you understand how to implement reusable software components by inheriting common logic and providing concrete details, demonstrated with configuration management examples like JSON and INI formats. Gain insight into when to prefer Template over Strategy for component design.

The pattern that we’re going to analyze next is called the Template pattern and it has a lot in common with the Strategy pattern. The Template pattern defines an abstract class that implements the skeleton (representing the common parts) of a component, where some of its steps are left undefined. Subclasses can then fill the gaps in the component by implementing the missing parts, called template methods. The intent of this pattern is to make it possible to define a family of classes that are all variations of a family of components. The following UML illustration shows the structure that we just described:

UML illustration of the Template pattern
UML illustration of the Template pattern

The three concrete classes shown in the above illustration extend the template class and provide an implementation for the templateMethod(), function, which is abstract or pure virtual, to use C++ terminology. In JavaScript, we don’t have a formal way to define abstract classes, so all we can do is leave the method undefined or ...