Template Pattern Definition: Defines the skeleton of an algorithm in an operation, delaying execution of some steps into its subclasses.
In fact, Java abstract class is template mode, so the use is very common. And it's easy to understand and use, let's start with an example:
Copy Code code as follows:
Public abstract class Benchmark
{
/**
* The following operation is what we want to do in the subclass
*/
public abstract void benchmark ();
/**
* Repeated execution of benchmark times
*/
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:
Copy Code code as follows:
public class Methodbenchmark extends Benchmark
{
/**
* Real definition of benchmark content
*/
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? See how to use:
Copy Code code as follows:
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.