An example of the Template Method pattern in Java
Let's see an example of how to use the Template Method pattern for a user interface design and usability scenario. Suppose you want to create a web application that allows users to generate different types of reports, such as HTML, PDF, or CSV. You can use the Template Method pattern to define a common algorithm for generating reports, and let the subclasses handle the specific details of each format.
First, you need to define an abstract superclass called ReportGenerator, that contains the template method and the abstract methods:
public abstract class ReportGenerator {
// The template method
public final void generateReport(String data) {
// Step 1: Validate the data
validateData(data);
// Step 2: Format the data
String formattedData = formatData(data);
// Step 3: Export the data
exportData(formattedData);
}
// The abstract methods
protected abstract void validateData(String data);
protected abstract String formatData(String data);
protected abstract void exportData(String formattedData);
}
Next, you need to define concrete subclasses that inherit from ReportGenerator, and override the abstract methods to provide their own implementations. For example, you can define a subclass called HTMLReportGenerator, that generates HTML reports:
public class HTMLReportGenerator extends ReportGenerator {
// Override the abstract methods
@Override
protected void validateData(String data) {
// Validate the data for HTML format
System.out.println("Validating data for HTML format...");
}
@Override
protected String formatData(String data) {
// Format the data for HTML format
System.out.println("Formatting data for HTML format...");
return "<html><body>" + data + "</body></html>";
}
@Override
protected void exportData(String formattedData) {
// Export the data for HTML format
System.out.println("Exporting data for HTML format...");
System.out.println(formattedData);
}
}
Similarly, you can define other subclasses for PDF and CSV formats. Finally, you can create instances of the concrete subclasses and invoke the template method:
public class Main {
public static void main(String[] args) {
// Create a sample data
String data = "This is a sample report";
// Create a HTML report generator
ReportGenerator htmlReportGenerator = new HTMLReportGenerator();
// Generate a HTML report
htmlReportGenerator.generateReport(data);
// Create a PDF report generator
ReportGenerator pdfReportGenerator = new PDFReportGenerator();
// Generate a PDF report
pdfReportGenerator.generateReport(data);
// Create a CSV report generator
ReportGenerator csvReportGenerator = new CSVReportGenerator();
// Generate a CSV report
csvReportGenerator.generateReport(data);
}
}