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 allows subclasses to redefine certain steps of an algorithm without changing its structure. It is particularly useful when you want to ensure a consistent process flow while allowing flexibility in specific parts of the process.
The Template Method pattern involves two main components:
The key idea is to define a template method that outlines the steps of an algorithm and delegates some of these steps to concrete methods that can be overridden by subclasses.
Let's illustrate the Template Method pattern with a practical example. Suppose we are developing a software system for different types of document processing, such as PDF and Word documents. We want to ensure that each document type follows a consistent processing flow but allows specific details to vary.
First, we define an abstract class DocumentProcessor that outlines the general steps of document processing:
1abstract class DocumentProcessor {2// Template method3process() {4this.open();5this.parse();6this.format();7this.save();8}910// Abstract methods to be implemented by subclasses11abstract open();12abstract parse();13abstract format();14abstract save();15}
Next, we create concrete classes for different document types, such as PDFProcessor and WordProcessor, that implement the abstract methods:
1class PDFProcessor extends DocumentProcessor {2open() {3console.log("Opening PDF file.");4}56parse() {7console.log("Parsing PDF content.");8}910format() {11console.log("Formatting PDF document.");12}1314save() {15console.log("Saving PDF file.");16}17}1819class WordProcessor extends DocumentProcessor {20open() {21console.log("Opening Word file.");22}2324parse() {25console.log("Parsing Word content.");26}2728format() {29console.log("Formatting Word document.");30}3132save() {33console.log("Saving Word file.");34}35}
Finally, we can use these concrete classes to process different types of documents:
1const pdfProcessor = new PDFProcessor();2pdfProcessor.process();34console.log("5");67const wordProcessor = new WordProcessor();8wordProcessor.process();
When you run the above code, you will see the following output:
Opening PDF file. Parsing PDF content. Formatting PDF document. Saving PDF file. Opening Word file. Parsing Word content. Formatting Word document. Saving Word file.
In this tutorial, we explored the Template Method pattern and how it can be used to define a consistent algorithm structure while allowing subclasses to implement specific details. In the next section, we will delve into another behavioral design pattern called the Visitor Pattern.
Info
The Template Method pattern is particularly useful in scenarios where you need to ensure a consistent process flow but allow for variations in specific steps. It promotes code reusability and makes it easier to extend the system with new document types.