Template template Pattern Definition:
Defines the skeleton of an algorithm in an operation, delaying execution of some steps into its subclasses.
When using Java abstract classes, the template pattern is often used, so template patterns are common. and easy to understand and use.
public abstract class Benchmark
{
/**
* 下面操作是我们希望在子类中完成
*/
public abstract void benchmark();
/**
* 重复执行benchmark次数
*/
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 previous example, we wanted to repeat the benchmark () operation, but the specifics of benchmark () were not described, but rather deferred to the subclass:
public class MethodBenchmark extends Benchmark
{
/**
* 真正定义benchmark内容
*/
public void benchmark() {
for (int i = 0; i < Integer.MAX_VALUE; i++){
System.out.printtln("i="+i);
}
}
}
At this point, template mode has been completed, is it very simple?
We call the Repeat method the template method, where the benchmark () implementation is deferred to the subclass Methodbenchmark implementation,
See how to use:
Benchmark operation = new Methodbenchmark ();
Long Duration = Operation.repeat (Integer.parseint (Args[0].trim ()));
System.out.println ("The operation took" + Duration + "milliseconds");
Perhaps you have wondered what the use of abstract classes is, and now you should understand them completely? As for the benefits of doing so, obviously ah, scalability, and later benchmark content changes, I just do an inheritance subclass can, do not have to modify other application code.