Sub topic 16
The Template Method Pattern
This chapter covers two ideas. The first is a design pattern built on abstract classes. The second is a short way to implement small interfaces.
The Template Method Pattern
A design pattern is a proven way to solve a common coding problem. The template method pattern fixes the order of steps in an algorithm. Subclasses fill in only the steps that change.
The fixed method is marked final. A final method is a method that subclasses cannot override, so no subclass can change the order of the steps.
abstract class DataReport {
public final String generate() {
return header() + "\n" + body() + "\n" + footer();
}
protected String header() {
return "=== Report ===";
}
protected abstract String body();
protected String footer() {
return "=== End ===";
}
}
class SalesReport extends DataReport {
@Override
protected String body() {
return "Total sales: 42";
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new SalesReport().generate());
}
}This prints:
=== Report ===
Total sales: 42
=== End ===Here is how it works:
generate()is the template method. It always runs header, then body, then footer.body()is abstract, so every report must write its own.header()andfooter()have default bodies. A subclass may override them, but it does not have to.
Functional Interfaces and Lambdas
A functional interface is an interface with exactly one abstract method. You can implement it with a lambda expression. A lambda expression is a short, unnamed function written as (parameters) -> result.
@FunctionalInterface
interface Calculator {
int apply(int a, int b);
}
public class Main {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b;
Calculator multiply = (a, b) -> a * b;
System.out.println(add.apply(3, 4)); // prints: 7
System.out.println(multiply.apply(3, 4)); // prints: 12
}
}The lambda (a, b) -> a + b is the body of apply. Java knows this because Calculator has only one abstract method. You do not need to write a full class.
The @FunctionalInterface annotation is optional. It asks the compiler to check the rule. If you add a second abstract method, the code will not compile.
| Way to implement `Calculator` | Code needed |
|---|---|
| Named class | A new class with an `apply` method |
| Lambda | `(a, b) -> a + b` |
Exercise
In DataReport, why is generate() marked final?
Show answer
So subclasses cannot override it and change the order of steps. They can only change the steps, such as body().
Exercise
Write a lambda that implements Calculator and returns the larger of a and b.
Show answer
Calculator max = (a, b) -> a > b ? a : b;
Exercise
An interface has two abstract methods. Can you implement it with a lambda?
Show answer
No. A lambda can implement only an interface with exactly one abstract method.