Template definition:
Define the skeleton of an algorithm in an operation, and extend the rows of some steps to its subcategories.
In fact, the abstract type of Java is the template mode, so it is widely used. It is easy to understand and use. We will start with an example:
Public abstract class Benchmark { /** * The following operations we want to complete in subcategories */ Public abstract void benchmark (); /** * Duplicate row benchmark count */ 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 repeat the benchmark () operation, but we have not stated the specific content of benchmark, it is extended to its subcategories for description:
Public class methodbenchmark extends Benchmark { /** * Truly define benchmark content */ Public void benchmark (){ For (INT I = 0; I <integer. max_value; I ++ ){ System. Out. printtln ("I =" + I ); } } } |
So far, the template mode has been completed. Is it very simple? 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 ");
Maybe you still have doubts about the usage of abstract classes. Should you understand it now? As a result, it is very difficult to achieve this. It is scalable and the benchmark content changes in the future. I only need to make another commitment class, you do not need to modify other application tokens.