Java › Interfaces & Abstract Classes
How would you use an abstract class to implement the Template Method pattern, defining a fixed algorithm skeleton with some steps left abstract for subclasses to fill in?
IntermediateAnswer
An abstract class is particularly well-suited to the Template Method pattern (already covered in the design patterns topic) because, unlike an interface, it can provide a concrete, non-overridable (final) method defining the overall algorithm's fixed sequence, while declaring specific customization points as abstract methods that subclasses must implement -- an interface alone (even with default methods) can't achieve quite the same guarantee, since a default method CAN be overridden by an implementing class, potentially altering the intended algorithm sequence in a way a final template method in an abstract class specifically prevents.
public abstract class ReportGenerator {
public final void generate() { // fixed algorithm, cannot be overridden since it's final
String data = fetchData();
String formatted = formatData(data);
saveReport(formatted);
}
protected abstract String fetchData(); // subclasses MUST implement
protected abstract String formatData(String data); // subclasses MUST implement
protected void saveReport(String content) { System.out.println("Saving: " + content); } // shared default behavior
}Real-world example A reporting framework's abstract ReportGenerator class guarantees every report subtype follows the identical fetch-format-save sequence via a final generate() method, with individual report types (PdfReportGenerator, CsvReportGenerator) only needing to implement the specific fetchData() and formatData() steps relevant to their format, unable to accidentally alter the guaranteed overall sequence.