Template Schema Definition: Defines the skeleton of an algorithm in an operation, delaying execution of some steps into its subclasses.
In fact, Java abstract class is originally template mode, so the use is very common. And it's easy to understand and use, so let's start with an example:
Public Abstract classbenchmark{/*** The following action is what we want to do in the subclass*/ Public Abstract voidBenchmark (); /*** Repeated execution of benchmark times*/ Public Final LongRepeat (intcount) {if(Count <= 0)return0; Else{LongStartTime =System.currenttimemillis (); for(inti = 0; I < count; i++) benchmark (); LongStopTime =System.currenttimemillis (); returnStopTime-StartTime; } }}
In the previous example, we wanted to repeat the benchmark () operation, but the specifics of benchmark () were not explained but deferred to the description in its subclasses:
Public class extends benchmark{ /** * True definition of Benchmark content * /publicvoid Benchmark () { for (int i = 0; i < Integer.max_value; i++) {System.out.printtln ("i=" +< C13>i); }}}
At this point, template mode has been completed, is it very simple? See how to use:
New Methodbenchmark (); Long duration = Operation.repeat (Integer.parseint (args[0].trim ())); System.out.println ("The operation took" + Duration + "milliseconds");
Perhaps you have doubts about the use of abstract classes, now you should thoroughly understand it? As for the benefits of doing so, it is obvious that the extensibility is strong, later benchmark content changes, I just need to do one more inheriting subclass, do not have to modify other application code.
Java templates mode (template mode)