Template pattern definition: defines the skeleton of an algorithm in an operation, delaying the execution of some steps to its subclass.
In fact, Java abstract classes are originally Template patterns, so they are very common to use. And it's easy to understand and use, let's start with an example:
The code copy is as follows:
public abstract class Benchmark
{
/**
* The following operation is what we want to complete in the subclass*/
public abstract void benchmark();
/**
* Number of repeated benchmark execution*/
public final long repeat (int count) {
if (count <= 0)
return 0;
else {
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++)
benchmark();
long stopTime = System.currentTimeMillis();
return stopTime - startTime;
}
}
}
In the above example, we want to perform benchmark() operation repeatedly, but we do not specify the specific content of benchmark(), but delay it to its subclass description:
The code copy is as follows:
public class MethodBenchmark extends Benchmark
{
/**
* Really define benchmark content*/
public void benchmark() {
for (int i = 0; i < Integer.MAX_VALUE; i++){
System.out.printtln("i="+i);
}
}
}
At this point, the Template mode has been completed, isn’t it very simple? See how to use:
The code copy is as follows:
Benchmark operation = new MethodBenchmark();
long duration = operation.repeat(Integer.parseInt(args[0].trim()));
System.out.println("The operation took " + duration + " millionseconds");
Maybe you were wondering what the use of abstract classes is, but now you should understand it completely, right? As for the benefits of doing this, it is obvious that it is highly extensible. In the future, I just need to make an inherited subclass and do not need to modify other application codes.